1 //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines analysis_warnings::[Policy,Executor].
11 // Together they are used by Sema to issue warnings based on inexpensive
12 // static analysis algorithms in libAnalysis.
14 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/AnalysisBasedWarnings.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28 #include "clang/Analysis/Analyses/Consumed.h"
29 #include "clang/Analysis/Analyses/ReachableCode.h"
30 #include "clang/Analysis/Analyses/ThreadSafety.h"
31 #include "clang/Analysis/Analyses/UninitializedValues.h"
32 #include "clang/Analysis/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/CFGStmtMap.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/MapVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/Support/Casting.h"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Unreachable code analysis.
54 //===----------------------------------------------------------------------===//
57 class UnreachableCodeHandler : public reachable_code::Callback {
59 SourceRange PreviousSilenceableCondVal;
62 UnreachableCodeHandler(Sema &s) : S(s) {}
64 void HandleUnreachable(reachable_code::UnreachableKind UK,
66 SourceRange SilenceableCondVal,
68 SourceRange R2) override {
69 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
75 PreviousSilenceableCondVal = SilenceableCondVal;
77 unsigned diag = diag::warn_unreachable;
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
82 case reachable_code::UK_Return:
83 diag = diag::warn_unreachable_return;
85 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
88 case reachable_code::UK_Other:
92 S.Diag(L, diag) << R1 << R2;
94 SourceLocation Open = SilenceableCondVal.getBegin();
96 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
98 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
106 } // anonymous namespace
108 /// CheckUnreachable - Check for unreachable code.
109 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
120 UnreachableCodeHandler UC(S);
121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
125 /// 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 // Returns true if every path from the entry block passes through a call to FD.
204 static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
205 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
206 llvm::SmallVector<CFGBlock *, 16> WorkList;
207 // Keep track of whether we found at least one recursive path.
208 bool foundRecursion = false;
210 const unsigned ExitID = cfg->getExit().getBlockID();
212 // Seed the work list with the entry block.
213 WorkList.push_back(&cfg->getEntry());
215 while (!WorkList.empty()) {
216 CFGBlock *Block = WorkList.pop_back_val();
218 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
219 if (CFGBlock *SuccBlock = *I) {
220 if (!Visited.insert(SuccBlock).second)
223 // Found a path to the exit node without a recursive call.
224 if (ExitID == SuccBlock->getBlockID())
227 // If the successor block contains a recursive call, end analysis there.
228 if (hasRecursiveCallInPath(FD, *SuccBlock)) {
229 foundRecursion = true;
233 WorkList.push_back(SuccBlock);
237 return foundRecursion;
240 static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
241 const Stmt *Body, AnalysisDeclContext &AC) {
242 FD = FD->getCanonicalDecl();
244 // Only run on non-templated functions and non-templated members of
245 // templated classes.
246 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
247 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
250 CFG *cfg = AC.getCFG();
253 // Emit diagnostic if a recursive function call is detected for all paths.
254 if (checkForRecursiveFunctionCall(FD, cfg))
255 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
258 //===----------------------------------------------------------------------===//
259 // Check for throw in a non-throwing function.
260 //===----------------------------------------------------------------------===//
262 /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
263 /// can reach ExitBlock.
264 static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
266 SmallVector<CFGBlock *, 16> Stack;
267 llvm::BitVector Queued(Body->getNumBlockIDs());
269 Stack.push_back(&ThrowBlock);
270 Queued[ThrowBlock.getBlockID()] = true;
272 while (!Stack.empty()) {
273 CFGBlock &UnwindBlock = *Stack.back();
276 for (auto &Succ : UnwindBlock.succs()) {
277 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
280 if (Succ->getBlockID() == Body->getExit().getBlockID())
284 dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
285 QualType Caught = Catch->getCaughtType();
286 if (Caught.isNull() || // catch (...) catches everything
287 !E->getSubExpr() || // throw; is considered cuaght by any handler
288 S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
289 // Exception doesn't escape via this path.
292 Stack.push_back(Succ);
293 Queued[Succ->getBlockID()] = true;
301 static void visitReachableThrows(
303 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
304 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
305 clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
306 for (CFGBlock *B : *BodyCFG) {
307 if (!Reachable[B->getBlockID()])
309 for (CFGElement &E : *B) {
310 Optional<CFGStmt> S = E.getAs<CFGStmt>();
313 if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
319 static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
320 const FunctionDecl *FD) {
321 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
322 FD->getTypeSourceInfo()) {
323 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
324 if (S.getLangOpts().CPlusPlus11 &&
325 (isa<CXXDestructorDecl>(FD) ||
326 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
327 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
328 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
329 getAs<FunctionProtoType>())
330 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
331 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
332 << FD->getExceptionSpecSourceRange();
334 S.Diag(FD->getLocation(), diag::note_throw_in_function)
335 << FD->getExceptionSpecSourceRange();
339 static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
340 AnalysisDeclContext &AC) {
341 CFG *BodyCFG = AC.getCFG();
344 if (BodyCFG->getExit().pred_empty())
346 visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
347 if (throwEscapes(S, Throw, Block, BodyCFG))
348 EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
352 static bool isNoexcept(const FunctionDecl *FD) {
353 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
354 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
359 //===----------------------------------------------------------------------===//
360 // Check for missing return value.
361 //===----------------------------------------------------------------------===//
363 enum ControlFlowKind {
368 NeverFallThroughOrReturn
371 /// CheckFallThrough - Check that we don't fall off the end of a
372 /// Statement that should return a value.
374 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
375 /// MaybeFallThrough iff we might or might not fall off the end,
376 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
377 /// return. We assume NeverFallThrough iff we never fall off the end of the
378 /// statement but we may return. We assume that functions not marked noreturn
380 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
381 CFG *cfg = AC.getCFG();
382 if (!cfg) return UnknownFallThrough;
384 // The CFG leaves in dead things, and we don't want the dead code paths to
385 // confuse us, so we mark all live things first.
386 llvm::BitVector live(cfg->getNumBlockIDs());
387 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
390 bool AddEHEdges = AC.getAddEHEdges();
391 if (!AddEHEdges && count != cfg->getNumBlockIDs())
392 // When there are things remaining dead, and we didn't add EH edges
393 // from CallExprs to the catch clauses, we have to go back and
394 // mark them as live.
395 for (const auto *B : *cfg) {
396 if (!live[B->getBlockID()]) {
397 if (B->pred_begin() == B->pred_end()) {
398 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
399 // When not adding EH edges from calls, catch clauses
400 // can otherwise seem dead. Avoid noting them as dead.
401 count += reachable_code::ScanReachableFromBlock(B, live);
407 // Now we know what is live, we check the live precessors of the exit block
408 // and look for fall through paths, being careful to ignore normal returns,
409 // and exceptional paths.
410 bool HasLiveReturn = false;
411 bool HasFakeEdge = false;
412 bool HasPlainEdge = false;
413 bool HasAbnormalEdge = false;
415 // Ignore default cases that aren't likely to be reachable because all
416 // enums in a switch(X) have explicit case statements.
417 CFGBlock::FilterOptions FO;
418 FO.IgnoreDefaultsWithCoveredEnums = 1;
420 for (CFGBlock::filtered_pred_iterator I =
421 cfg->getExit().filtered_pred_start_end(FO);
423 const CFGBlock &B = **I;
424 if (!live[B.getBlockID()])
427 // Skip blocks which contain an element marked as no-return. They don't
428 // represent actually viable edges into the exit block, so mark them as
430 if (B.hasNoReturnElement()) {
431 HasAbnormalEdge = true;
435 // Destructors can appear after the 'return' in the CFG. This is
436 // normal. We need to look pass the destructors for the return
437 // statement (if it exists).
438 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
440 for ( ; ri != re ; ++ri)
441 if (ri->getAs<CFGStmt>())
444 // No more CFGElements in the block?
446 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
447 HasAbnormalEdge = true;
450 // A labeled empty statement, or the entry block...
455 CFGStmt CS = ri->castAs<CFGStmt>();
456 const Stmt *S = CS.getStmt();
457 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
458 HasLiveReturn = true;
461 if (isa<ObjCAtThrowStmt>(S)) {
465 if (isa<CXXThrowExpr>(S)) {
469 if (isa<MSAsmStmt>(S)) {
470 // TODO: Verify this is correct.
472 HasLiveReturn = true;
475 if (isa<CXXTryStmt>(S)) {
476 HasAbnormalEdge = true;
479 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
481 HasAbnormalEdge = true;
489 return NeverFallThrough;
490 return NeverFallThroughOrReturn;
492 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
493 return MaybeFallThrough;
494 // This says AlwaysFallThrough for calls to functions that are not marked
495 // noreturn, that don't return. If people would like this warning to be more
496 // accurate, such functions should be marked as noreturn.
497 return AlwaysFallThrough;
502 struct CheckFallThroughDiagnostics {
503 unsigned diag_MaybeFallThrough_HasNoReturn;
504 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
505 unsigned diag_AlwaysFallThrough_HasNoReturn;
506 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
507 unsigned diag_NeverFallThroughOrReturn;
508 enum { Function, Block, Lambda, Coroutine } funMode;
509 SourceLocation FuncLoc;
511 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
512 CheckFallThroughDiagnostics D;
513 D.FuncLoc = Func->getLocation();
514 D.diag_MaybeFallThrough_HasNoReturn =
515 diag::warn_falloff_noreturn_function;
516 D.diag_MaybeFallThrough_ReturnsNonVoid =
517 diag::warn_maybe_falloff_nonvoid_function;
518 D.diag_AlwaysFallThrough_HasNoReturn =
519 diag::warn_falloff_noreturn_function;
520 D.diag_AlwaysFallThrough_ReturnsNonVoid =
521 diag::warn_falloff_nonvoid_function;
523 // Don't suggest that virtual functions be marked "noreturn", since they
524 // might be overridden by non-noreturn functions.
525 bool isVirtualMethod = false;
526 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
527 isVirtualMethod = Method->isVirtual();
529 // Don't suggest that template instantiations be marked "noreturn"
530 bool isTemplateInstantiation = false;
531 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
532 isTemplateInstantiation = Function->isTemplateInstantiation();
534 if (!isVirtualMethod && !isTemplateInstantiation)
535 D.diag_NeverFallThroughOrReturn =
536 diag::warn_suggest_noreturn_function;
538 D.diag_NeverFallThroughOrReturn = 0;
540 D.funMode = Function;
544 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
545 CheckFallThroughDiagnostics D;
546 D.FuncLoc = Func->getLocation();
547 D.diag_MaybeFallThrough_HasNoReturn = 0;
548 D.diag_MaybeFallThrough_ReturnsNonVoid =
549 diag::warn_maybe_falloff_nonvoid_coroutine;
550 D.diag_AlwaysFallThrough_HasNoReturn = 0;
551 D.diag_AlwaysFallThrough_ReturnsNonVoid =
552 diag::warn_falloff_nonvoid_coroutine;
553 D.funMode = Coroutine;
557 static CheckFallThroughDiagnostics MakeForBlock() {
558 CheckFallThroughDiagnostics D;
559 D.diag_MaybeFallThrough_HasNoReturn =
560 diag::err_noreturn_block_has_return_expr;
561 D.diag_MaybeFallThrough_ReturnsNonVoid =
562 diag::err_maybe_falloff_nonvoid_block;
563 D.diag_AlwaysFallThrough_HasNoReturn =
564 diag::err_noreturn_block_has_return_expr;
565 D.diag_AlwaysFallThrough_ReturnsNonVoid =
566 diag::err_falloff_nonvoid_block;
567 D.diag_NeverFallThroughOrReturn = 0;
572 static CheckFallThroughDiagnostics MakeForLambda() {
573 CheckFallThroughDiagnostics D;
574 D.diag_MaybeFallThrough_HasNoReturn =
575 diag::err_noreturn_lambda_has_return_expr;
576 D.diag_MaybeFallThrough_ReturnsNonVoid =
577 diag::warn_maybe_falloff_nonvoid_lambda;
578 D.diag_AlwaysFallThrough_HasNoReturn =
579 diag::err_noreturn_lambda_has_return_expr;
580 D.diag_AlwaysFallThrough_ReturnsNonVoid =
581 diag::warn_falloff_nonvoid_lambda;
582 D.diag_NeverFallThroughOrReturn = 0;
587 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
588 bool HasNoReturn) const {
589 if (funMode == Function) {
590 return (ReturnsVoid ||
591 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
594 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
597 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
599 if (funMode == Coroutine) {
600 return (ReturnsVoid ||
601 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
602 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
606 // For blocks / lambdas.
607 return ReturnsVoid && !HasNoReturn;
611 } // anonymous namespace
613 /// CheckFallThroughForBody - Check that we don't fall off the end of a
614 /// function that should return a value. Check that we don't fall off the end
615 /// of a noreturn function. We assume that functions and blocks not marked
616 /// noreturn will return.
617 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
618 const BlockExpr *blkExpr,
619 const CheckFallThroughDiagnostics &CD,
620 AnalysisDeclContext &AC,
621 sema::FunctionScopeInfo *FSI) {
623 bool ReturnsVoid = false;
624 bool HasNoReturn = false;
625 bool IsCoroutine = FSI->isCoroutine();
627 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
628 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
629 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
631 ReturnsVoid = FD->getReturnType()->isVoidType();
632 HasNoReturn = FD->isNoReturn();
634 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
635 ReturnsVoid = MD->getReturnType()->isVoidType();
636 HasNoReturn = MD->hasAttr<NoReturnAttr>();
638 else if (isa<BlockDecl>(D)) {
639 QualType BlockTy = blkExpr->getType();
640 if (const FunctionType *FT =
641 BlockTy->getPointeeType()->getAs<FunctionType>()) {
642 if (FT->getReturnType()->isVoidType())
644 if (FT->getNoReturnAttr())
649 DiagnosticsEngine &Diags = S.getDiagnostics();
651 // Short circuit for compilation speed.
652 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
654 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
655 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
657 S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
662 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
663 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
666 // Either in a function body compound statement, or a function-try-block.
667 switch (CheckFallThrough(AC)) {
668 case UnknownFallThrough:
671 case MaybeFallThrough:
673 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
674 else if (!ReturnsVoid)
675 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
677 case AlwaysFallThrough:
679 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
680 else if (!ReturnsVoid)
681 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
683 case NeverFallThroughOrReturn:
684 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
685 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
686 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
687 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
688 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
690 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
694 case NeverFallThrough:
699 //===----------------------------------------------------------------------===//
701 //===----------------------------------------------------------------------===//
704 /// ContainsReference - A visitor class to search for references to
705 /// a particular declaration (the needle) within any evaluated component of an
706 /// expression (recursively).
707 class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
709 const DeclRefExpr *Needle;
712 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
714 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
715 : Inherited(Context), FoundReference(false), Needle(Needle) {}
717 void VisitExpr(const Expr *E) {
718 // Stop evaluating if we already have a reference.
722 Inherited::VisitExpr(E);
725 void VisitDeclRefExpr(const DeclRefExpr *E) {
727 FoundReference = true;
729 Inherited::VisitDeclRefExpr(E);
732 bool doesContainReference() const { return FoundReference; }
734 } // anonymous namespace
736 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
737 QualType VariableTy = VD->getType().getCanonicalType();
738 if (VariableTy->isBlockPointerType() &&
739 !VD->hasAttr<BlocksAttr>()) {
740 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
742 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
746 // Don't issue a fixit if there is already an initializer.
750 // Don't suggest a fixit inside macros.
751 if (VD->getLocEnd().isMacroID())
754 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
756 // Suggest possible initialization (if any).
757 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
761 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
762 << FixItHint::CreateInsertion(Loc, Init);
766 /// Create a fixit to remove an if-like statement, on the assumption that its
767 /// condition is CondVal.
768 static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
769 const Stmt *Else, bool CondVal,
770 FixItHint &Fixit1, FixItHint &Fixit2) {
772 // If condition is always true, remove all but the 'then'.
773 Fixit1 = FixItHint::CreateRemoval(
774 CharSourceRange::getCharRange(If->getLocStart(),
775 Then->getLocStart()));
777 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
778 Fixit2 = FixItHint::CreateRemoval(
779 SourceRange(ElseKwLoc, Else->getLocEnd()));
782 // If condition is always false, remove all but the 'else'.
784 Fixit1 = FixItHint::CreateRemoval(
785 CharSourceRange::getCharRange(If->getLocStart(),
786 Else->getLocStart()));
788 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
792 /// DiagUninitUse -- Helper function to produce a diagnostic for an
793 /// uninitialized use of a variable.
794 static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
795 bool IsCapturedByBlock) {
796 bool Diagnosed = false;
798 switch (Use.getKind()) {
799 case UninitUse::Always:
800 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
801 << VD->getDeclName() << IsCapturedByBlock
802 << Use.getUser()->getSourceRange();
805 case UninitUse::AfterDecl:
806 case UninitUse::AfterCall:
807 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
808 << VD->getDeclName() << IsCapturedByBlock
809 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
810 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
811 << VD->getSourceRange();
812 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
813 << IsCapturedByBlock << Use.getUser()->getSourceRange();
816 case UninitUse::Maybe:
817 case UninitUse::Sometimes:
818 // Carry on to report sometimes-uninitialized branches, if possible,
819 // or a 'may be used uninitialized' diagnostic otherwise.
823 // Diagnose each branch which leads to a sometimes-uninitialized use.
824 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
826 assert(Use.getKind() == UninitUse::Sometimes);
828 const Expr *User = Use.getUser();
829 const Stmt *Term = I->Terminator;
831 // Information used when building the diagnostic.
836 // FixIts to suppress the diagnostic by removing the dead condition.
837 // For all binary terminators, branch 0 is taken if the condition is true,
838 // and branch 1 is taken if the condition is false.
839 int RemoveDiagKind = -1;
840 const char *FixitStr =
841 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
842 : (I->Output ? "1" : "0");
843 FixItHint Fixit1, Fixit2;
845 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
847 // Don't know how to report this. Just fall back to 'may be used
848 // uninitialized'. FIXME: Can this happen?
851 // "condition is true / condition is false".
852 case Stmt::IfStmtClass: {
853 const IfStmt *IS = cast<IfStmt>(Term);
856 Range = IS->getCond()->getSourceRange();
858 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
859 I->Output, Fixit1, Fixit2);
862 case Stmt::ConditionalOperatorClass: {
863 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
866 Range = CO->getCond()->getSourceRange();
868 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
869 I->Output, Fixit1, Fixit2);
872 case Stmt::BinaryOperatorClass: {
873 const BinaryOperator *BO = cast<BinaryOperator>(Term);
874 if (!BO->isLogicalOp())
877 Str = BO->getOpcodeStr();
878 Range = BO->getLHS()->getSourceRange();
880 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
881 (BO->getOpcode() == BO_LOr && !I->Output))
882 // true && y -> y, false || y -> y.
883 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
884 BO->getOperatorLoc()));
886 // false && y -> false, true || y -> true.
887 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
891 // "loop is entered / loop is exited".
892 case Stmt::WhileStmtClass:
895 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
897 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
899 case Stmt::ForStmtClass:
902 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
905 Fixit1 = FixItHint::CreateRemoval(Range);
907 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
909 case Stmt::CXXForRangeStmtClass:
910 if (I->Output == 1) {
911 // The use occurs if a range-based for loop's body never executes.
912 // That may be impossible, and there's no syntactic fix for this,
913 // so treat it as a 'may be uninitialized' case.
918 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
921 // "condition is true / loop is exited".
922 case Stmt::DoStmtClass:
925 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
927 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
930 // "switch case is taken".
931 case Stmt::CaseStmtClass:
934 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
936 case Stmt::DefaultStmtClass:
939 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
943 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
944 << VD->getDeclName() << IsCapturedByBlock << DiagKind
945 << Str << I->Output << Range;
946 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
947 << IsCapturedByBlock << User->getSourceRange();
948 if (RemoveDiagKind != -1)
949 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
950 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
956 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
957 << VD->getDeclName() << IsCapturedByBlock
958 << Use.getUser()->getSourceRange();
961 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
962 /// uninitialized variable. This manages the different forms of diagnostic
963 /// emitted for particular types of uses. Returns true if the use was diagnosed
964 /// as a warning. If a particular use is one we omit warnings for, returns
966 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
967 const UninitUse &Use,
968 bool alwaysReportSelfInit = false) {
969 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
970 // Inspect the initializer of the variable declaration which is
971 // being referenced prior to its initialization. We emit
972 // specialized diagnostics for self-initialization, and we
973 // specifically avoid warning about self references which take the
978 // This is used to indicate to GCC that 'x' is intentionally left
979 // uninitialized. Proven code paths which access 'x' in
980 // an uninitialized state after this will still warn.
981 if (const Expr *Initializer = VD->getInit()) {
982 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
985 ContainsReference CR(S.Context, DRE);
986 CR.Visit(Initializer);
987 if (CR.doesContainReference()) {
988 S.Diag(DRE->getLocStart(),
989 diag::warn_uninit_self_reference_in_init)
990 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
995 DiagUninitUse(S, VD, Use, false);
997 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
998 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
999 S.Diag(BE->getLocStart(),
1000 diag::warn_uninit_byref_blockvar_captured_by_block)
1001 << VD->getDeclName();
1003 DiagUninitUse(S, VD, Use, true);
1006 // Report where the variable was declared when the use wasn't within
1007 // the initializer of that declaration & we didn't already suggest
1008 // an initialization fixit.
1009 if (!SuggestInitializationFixit(S, VD))
1010 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
1011 << VD->getDeclName();
1017 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1019 FallthroughMapper(Sema &S)
1020 : FoundSwitchStatements(false),
1024 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1026 void markFallthroughVisited(const AttributedStmt *Stmt) {
1027 bool Found = FallthroughStmts.erase(Stmt);
1032 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1034 const AttrStmts &getFallthroughStmts() const {
1035 return FallthroughStmts;
1038 void fillReachableBlocks(CFG *Cfg) {
1039 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1040 std::deque<const CFGBlock *> BlockQueue;
1042 ReachableBlocks.insert(&Cfg->getEntry());
1043 BlockQueue.push_back(&Cfg->getEntry());
1044 // Mark all case blocks reachable to avoid problems with switching on
1045 // constants, covered enums, etc.
1046 // These blocks can contain fall-through annotations, and we don't want to
1047 // issue a warn_fallthrough_attr_unreachable for them.
1048 for (const auto *B : *Cfg) {
1049 const Stmt *L = B->getLabel();
1050 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
1051 BlockQueue.push_back(B);
1054 while (!BlockQueue.empty()) {
1055 const CFGBlock *P = BlockQueue.front();
1056 BlockQueue.pop_front();
1057 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1060 if (*I && ReachableBlocks.insert(*I).second)
1061 BlockQueue.push_back(*I);
1066 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1067 bool IsTemplateInstantiation) {
1068 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1070 int UnannotatedCnt = 0;
1073 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
1074 while (!BlockQueue.empty()) {
1075 const CFGBlock *P = BlockQueue.front();
1076 BlockQueue.pop_front();
1079 const Stmt *Term = P->getTerminator();
1080 if (Term && isa<SwitchStmt>(Term))
1081 continue; // Switch statement, good.
1083 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1084 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1085 continue; // Previous case label has no statements, good.
1087 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1088 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1089 continue; // Case label is preceded with a normal label, good.
1091 if (!ReachableBlocks.count(P)) {
1092 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1093 ElemEnd = P->rend();
1094 ElemIt != ElemEnd; ++ElemIt) {
1095 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1096 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
1097 // Don't issue a warning for an unreachable fallthrough
1098 // attribute in template instantiations as it may not be
1099 // unreachable in all instantiations of the template.
1100 if (!IsTemplateInstantiation)
1101 S.Diag(AS->getLocStart(),
1102 diag::warn_fallthrough_attr_unreachable);
1103 markFallthroughVisited(AS);
1107 // Don't care about other unreachable statements.
1110 // If there are no unreachable statements, this may be a special
1113 // A a; // A has a destructor.
1116 // // <<<< This place is represented by a 'hanging' CFG block.
1121 const Stmt *LastStmt = getLastStmt(*P);
1122 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1123 markFallthroughVisited(AS);
1125 continue; // Fallthrough annotation, good.
1128 if (!LastStmt) { // This block contains no executable statements.
1129 // Traverse its predecessors.
1130 std::copy(P->pred_begin(), P->pred_end(),
1131 std::back_inserter(BlockQueue));
1137 return !!UnannotatedCnt;
1140 // RecursiveASTVisitor setup.
1141 bool shouldWalkTypesOfTypeLocs() const { return false; }
1143 bool VisitAttributedStmt(AttributedStmt *S) {
1144 if (asFallThroughAttr(S))
1145 FallthroughStmts.insert(S);
1149 bool VisitSwitchStmt(SwitchStmt *S) {
1150 FoundSwitchStatements = true;
1154 // We don't want to traverse local type declarations. We analyze their
1155 // methods separately.
1156 bool TraverseDecl(Decl *D) { return true; }
1158 // We analyze lambda bodies separately. Skip them here.
1159 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1163 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1164 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1165 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1171 static const Stmt *getLastStmt(const CFGBlock &B) {
1172 if (const Stmt *Term = B.getTerminator())
1174 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1176 ElemIt != ElemEnd; ++ElemIt) {
1177 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1178 return CS->getStmt();
1180 // Workaround to detect a statement thrown out by CFGBuilder:
1181 // case X: {} case Y:
1182 // case X: ; case Y:
1183 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1184 if (!isa<SwitchCase>(SW->getSubStmt()))
1185 return SW->getSubStmt();
1190 bool FoundSwitchStatements;
1191 AttrStmts FallthroughStmts;
1193 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1195 } // anonymous namespace
1197 static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1198 SourceLocation Loc) {
1199 TokenValue FallthroughTokens[] = {
1200 tok::l_square, tok::l_square,
1201 PP.getIdentifierInfo("fallthrough"),
1202 tok::r_square, tok::r_square
1205 TokenValue ClangFallthroughTokens[] = {
1206 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1207 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1208 tok::r_square, tok::r_square
1211 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
1213 StringRef MacroName;
1214 if (PreferClangAttr)
1215 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1216 if (MacroName.empty())
1217 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1218 if (MacroName.empty() && !PreferClangAttr)
1219 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1220 if (MacroName.empty())
1221 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1225 static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1227 // Only perform this analysis when using [[]] attributes. There is no good
1228 // workflow for this warning when not using C++11. There is no good way to
1229 // silence the warning (no attribute is available) unless we are using
1230 // [[]] attributes. One could use pragmas to silence the warning, but as a
1231 // general solution that is gross and not in the spirit of this warning.
1233 // NOTE: This an intermediate solution. There are on-going discussions on
1234 // how to properly support this warning outside of C++11 with an annotation.
1235 if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
1238 FallthroughMapper FM(S);
1239 FM.TraverseStmt(AC.getBody());
1241 if (!FM.foundSwitchStatements())
1244 if (PerFunction && FM.getFallthroughStmts().empty())
1247 CFG *Cfg = AC.getCFG();
1252 FM.fillReachableBlocks(Cfg);
1254 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
1255 const Stmt *Label = B->getLabel();
1257 if (!Label || !isa<SwitchCase>(Label))
1262 bool IsTemplateInstantiation = false;
1263 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1264 IsTemplateInstantiation = Function->isTemplateInstantiation();
1265 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1266 IsTemplateInstantiation))
1269 S.Diag(Label->getLocStart(),
1270 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1271 : diag::warn_unannotated_fallthrough);
1273 if (!AnnotatedCnt) {
1274 SourceLocation L = Label->getLocStart();
1277 if (S.getLangOpts().CPlusPlus11) {
1278 const Stmt *Term = B->getTerminator();
1279 // Skip empty cases.
1280 while (B->empty() && !Term && B->succ_size() == 1) {
1281 B = *B->succ_begin();
1282 Term = B->getTerminator();
1284 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1285 Preprocessor &PP = S.getPreprocessor();
1286 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
1287 SmallString<64> TextToInsert(AnnotationSpelling);
1288 TextToInsert += "; ";
1289 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1290 AnnotationSpelling <<
1291 FixItHint::CreateInsertion(L, TextToInsert);
1294 S.Diag(L, diag::note_insert_break_fixit) <<
1295 FixItHint::CreateInsertion(L, "break; ");
1299 for (const auto *F : FM.getFallthroughStmts())
1300 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
1303 static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1308 switch (S->getStmtClass()) {
1309 case Stmt::ForStmtClass:
1310 case Stmt::WhileStmtClass:
1311 case Stmt::CXXForRangeStmtClass:
1312 case Stmt::ObjCForCollectionStmtClass:
1314 case Stmt::DoStmtClass: {
1315 const Expr *Cond = cast<DoStmt>(S)->getCond();
1317 if (!Cond->EvaluateAsInt(Val, Ctx))
1319 return Val.getBoolValue();
1324 } while ((S = PM.getParent(S)));
1329 static void diagnoseRepeatedUseOfWeak(Sema &S,
1330 const sema::FunctionScopeInfo *CurFn,
1332 const ParentMap &PM) {
1333 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1334 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1335 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1336 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1339 ASTContext &Ctx = S.getASTContext();
1341 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1343 // Extract all weak objects that are referenced more than once.
1344 SmallVector<StmtUsesPair, 8> UsesByStmt;
1345 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1347 const WeakUseVector &Uses = I->second;
1349 // Find the first read of the weak object.
1350 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1351 for ( ; UI != UE; ++UI) {
1356 // If there were only writes to this object, don't warn.
1360 // If there was only one read, followed by any number of writes, and the
1361 // read is not within a loop, don't warn. Additionally, don't warn in a
1362 // loop if the base object is a local variable -- local variables are often
1363 // changed in loops.
1364 if (UI == Uses.begin()) {
1365 WeakUseVector::const_iterator UI2 = UI;
1366 for (++UI2; UI2 != UE; ++UI2)
1367 if (UI2->isUnsafe())
1371 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1374 const WeakObjectProfileTy &Profile = I->first;
1375 if (!Profile.isExactProfile())
1378 const NamedDecl *Base = Profile.getBase();
1380 Base = Profile.getProperty();
1381 assert(Base && "A profile always has a base or property.");
1383 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1384 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1389 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1392 if (UsesByStmt.empty())
1395 // Sort by first use so that we emit the warnings in a deterministic order.
1396 SourceManager &SM = S.getSourceManager();
1397 llvm::sort(UsesByStmt.begin(), UsesByStmt.end(),
1398 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1399 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1400 RHS.first->getLocStart());
1403 // Classify the current code body for better warning text.
1404 // This enum should stay in sync with the cases in
1405 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1406 // FIXME: Should we use a common classification enum and the same set of
1407 // possibilities all throughout Sema?
1415 if (isa<sema::BlockScopeInfo>(CurFn))
1416 FunctionKind = Block;
1417 else if (isa<sema::LambdaScopeInfo>(CurFn))
1418 FunctionKind = Lambda;
1419 else if (isa<ObjCMethodDecl>(D))
1420 FunctionKind = Method;
1422 FunctionKind = Function;
1424 // Iterate through the sorted problems and emit warnings for each.
1425 for (const auto &P : UsesByStmt) {
1426 const Stmt *FirstRead = P.first;
1427 const WeakObjectProfileTy &Key = P.second->first;
1428 const WeakUseVector &Uses = P.second->second;
1430 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1431 // may not contain enough information to determine that these are different
1432 // properties. We can only be 100% sure of a repeated use in certain cases,
1433 // and we adjust the diagnostic kind accordingly so that the less certain
1434 // case can be turned off if it is too noisy.
1436 if (Key.isExactProfile())
1437 DiagKind = diag::warn_arc_repeated_use_of_weak;
1439 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1441 // Classify the weak object being accessed for better warning text.
1442 // This enum should stay in sync with the cases in
1443 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1451 const NamedDecl *KeyProp = Key.getProperty();
1452 if (isa<VarDecl>(KeyProp))
1453 ObjectKind = Variable;
1454 else if (isa<ObjCPropertyDecl>(KeyProp))
1455 ObjectKind = Property;
1456 else if (isa<ObjCMethodDecl>(KeyProp))
1457 ObjectKind = ImplicitProperty;
1458 else if (isa<ObjCIvarDecl>(KeyProp))
1461 llvm_unreachable("Unexpected weak object kind!");
1463 // Do not warn about IBOutlet weak property receivers being set to null
1464 // since they are typically only used from the main thread.
1465 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
1466 if (Prop->hasAttr<IBOutletAttr>())
1469 // Show the first time the object was read.
1470 S.Diag(FirstRead->getLocStart(), DiagKind)
1471 << int(ObjectKind) << KeyProp << int(FunctionKind)
1472 << FirstRead->getSourceRange();
1474 // Print all the other accesses as notes.
1475 for (const auto &Use : Uses) {
1476 if (Use.getUseExpr() == FirstRead)
1478 S.Diag(Use.getUseExpr()->getLocStart(),
1479 diag::note_arc_weak_also_accessed_here)
1480 << Use.getUseExpr()->getSourceRange();
1486 class UninitValsDiagReporter : public UninitVariablesHandler {
1488 typedef SmallVector<UninitUse, 2> UsesVec;
1489 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1490 // Prefer using MapVector to DenseMap, so that iteration order will be
1491 // the same as insertion order. This is needed to obtain a deterministic
1492 // order of diagnostics when calling flushDiagnostics().
1493 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1497 UninitValsDiagReporter(Sema &S) : S(S) {}
1498 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1500 MappedType &getUses(const VarDecl *vd) {
1501 MappedType &V = uses[vd];
1502 if (!V.getPointer())
1503 V.setPointer(new UsesVec());
1507 void handleUseOfUninitVariable(const VarDecl *vd,
1508 const UninitUse &use) override {
1509 getUses(vd).getPointer()->push_back(use);
1512 void handleSelfInit(const VarDecl *vd) override {
1513 getUses(vd).setInt(true);
1516 void flushDiagnostics() {
1517 for (const auto &P : uses) {
1518 const VarDecl *vd = P.first;
1519 const MappedType &V = P.second;
1521 UsesVec *vec = V.getPointer();
1522 bool hasSelfInit = V.getInt();
1524 // Specially handle the case where we have uses of an uninitialized
1525 // variable, but the root cause is an idiomatic self-init. We want
1526 // to report the diagnostic at the self-init since that is the root cause.
1527 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1528 DiagnoseUninitializedUse(S, vd,
1529 UninitUse(vd->getInit()->IgnoreParenCasts(),
1530 /* isAlwaysUninit */ true),
1531 /* alwaysReportSelfInit */ true);
1533 // Sort the uses by their SourceLocations. While not strictly
1534 // guaranteed to produce them in line/column order, this will provide
1535 // a stable ordering.
1536 llvm::sort(vec->begin(), vec->end(),
1537 [](const UninitUse &a, const UninitUse &b) {
1538 // Prefer a more confident report over a less confident one.
1539 if (a.getKind() != b.getKind())
1540 return a.getKind() > b.getKind();
1541 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1544 for (const auto &U : *vec) {
1545 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1546 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1548 if (DiagnoseUninitializedUse(S, vd, Use))
1549 // Skip further diagnostics for this variable. We try to warn only
1550 // on the first point at which a variable is used uninitialized.
1555 // Release the uses vector.
1563 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1564 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1565 return U.getKind() == UninitUse::Always ||
1566 U.getKind() == UninitUse::AfterCall ||
1567 U.getKind() == UninitUse::AfterDecl;
1571 } // anonymous namespace
1575 typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1576 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1577 typedef std::list<DelayedDiag> DiagList;
1579 struct SortDiagBySourceLocation {
1581 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1583 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1584 // Although this call will be slow, this is only called when outputting
1585 // multiple warnings.
1586 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1589 } // anonymous namespace
1590 } // namespace clang
1592 //===----------------------------------------------------------------------===//
1594 //===----------------------------------------------------------------------===//
1596 namespace threadSafety {
1598 class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1601 SourceLocation FunLocation, FunEndLocation;
1603 const FunctionDecl *CurrentFunction;
1606 OptionalNotes getNotes() const {
1607 if (Verbose && CurrentFunction) {
1608 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1609 S.PDiag(diag::note_thread_warning_in_fun)
1610 << CurrentFunction);
1611 return OptionalNotes(1, FNote);
1613 return OptionalNotes();
1616 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1617 OptionalNotes ONS(1, Note);
1618 if (Verbose && CurrentFunction) {
1619 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1620 S.PDiag(diag::note_thread_warning_in_fun)
1621 << CurrentFunction);
1622 ONS.push_back(std::move(FNote));
1627 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1628 const PartialDiagnosticAt &Note2) const {
1630 ONS.push_back(Note1);
1631 ONS.push_back(Note2);
1632 if (Verbose && CurrentFunction) {
1633 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1634 S.PDiag(diag::note_thread_warning_in_fun)
1635 << CurrentFunction);
1636 ONS.push_back(std::move(FNote));
1642 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1643 SourceLocation Loc) {
1644 // Gracefully handle rare cases when the analysis can't get a more
1645 // precise source location.
1648 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1649 Warnings.emplace_back(std::move(Warning), getNotes());
1653 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1654 : S(S), FunLocation(FL), FunEndLocation(FEL),
1655 CurrentFunction(nullptr), Verbose(false) {}
1657 void setVerbose(bool b) { Verbose = b; }
1659 /// Emit all buffered diagnostics in order of sourcelocation.
1660 /// We need to output diagnostics produced while iterating through
1661 /// the lockset in deterministic order, so this function orders diagnostics
1662 /// and outputs them.
1663 void emitDiagnostics() {
1664 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1665 for (const auto &Diag : Warnings) {
1666 S.Diag(Diag.first.first, Diag.first.second);
1667 for (const auto &Note : Diag.second)
1668 S.Diag(Note.first, Note.second);
1672 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1673 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1675 Warnings.emplace_back(std::move(Warning), getNotes());
1678 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1679 SourceLocation Loc) override {
1680 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1683 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1684 LockKind Expected, LockKind Received,
1685 SourceLocation Loc) override {
1686 if (Loc.isInvalid())
1688 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1689 << Kind << LockName << Received
1691 Warnings.emplace_back(std::move(Warning), getNotes());
1694 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1695 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1698 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1699 SourceLocation LocLocked,
1700 SourceLocation LocEndOfScope,
1701 LockErrorKind LEK) override {
1702 unsigned DiagID = 0;
1704 case LEK_LockedSomePredecessors:
1705 DiagID = diag::warn_lock_some_predecessors;
1707 case LEK_LockedSomeLoopIterations:
1708 DiagID = diag::warn_expecting_lock_held_on_loop;
1710 case LEK_LockedAtEndOfFunction:
1711 DiagID = diag::warn_no_unlock;
1713 case LEK_NotLockedAtEndOfFunction:
1714 DiagID = diag::warn_expecting_locked;
1717 if (LocEndOfScope.isInvalid())
1718 LocEndOfScope = FunEndLocation;
1720 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1722 if (LocLocked.isValid()) {
1723 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1725 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1728 Warnings.emplace_back(std::move(Warning), getNotes());
1731 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1732 SourceLocation Loc1,
1733 SourceLocation Loc2) override {
1734 PartialDiagnosticAt Warning(Loc1,
1735 S.PDiag(diag::warn_lock_exclusive_and_shared)
1736 << Kind << LockName);
1737 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1738 << Kind << LockName);
1739 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1742 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1743 ProtectedOperationKind POK, AccessKind AK,
1744 SourceLocation Loc) override {
1745 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1746 "Only works for variables");
1747 unsigned DiagID = POK == POK_VarAccess?
1748 diag::warn_variable_requires_any_lock:
1749 diag::warn_var_deref_requires_any_lock;
1750 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1751 << D << getLockKindFromAccessKind(AK));
1752 Warnings.emplace_back(std::move(Warning), getNotes());
1755 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1756 ProtectedOperationKind POK, Name LockName,
1757 LockKind LK, SourceLocation Loc,
1758 Name *PossibleMatch) override {
1759 unsigned DiagID = 0;
1760 if (PossibleMatch) {
1763 DiagID = diag::warn_variable_requires_lock_precise;
1765 case POK_VarDereference:
1766 DiagID = diag::warn_var_deref_requires_lock_precise;
1768 case POK_FunctionCall:
1769 DiagID = diag::warn_fun_requires_lock_precise;
1772 DiagID = diag::warn_guarded_pass_by_reference;
1774 case POK_PtPassByRef:
1775 DiagID = diag::warn_pt_guarded_pass_by_reference;
1778 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1781 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1783 if (Verbose && POK == POK_VarAccess) {
1784 PartialDiagnosticAt VNote(D->getLocation(),
1785 S.PDiag(diag::note_guarded_by_declared_here)
1786 << D->getNameAsString());
1787 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1789 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1793 DiagID = diag::warn_variable_requires_lock;
1795 case POK_VarDereference:
1796 DiagID = diag::warn_var_deref_requires_lock;
1798 case POK_FunctionCall:
1799 DiagID = diag::warn_fun_requires_lock;
1802 DiagID = diag::warn_guarded_pass_by_reference;
1804 case POK_PtPassByRef:
1805 DiagID = diag::warn_pt_guarded_pass_by_reference;
1808 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1811 if (Verbose && POK == POK_VarAccess) {
1812 PartialDiagnosticAt Note(D->getLocation(),
1813 S.PDiag(diag::note_guarded_by_declared_here));
1814 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1816 Warnings.emplace_back(std::move(Warning), getNotes());
1820 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1821 SourceLocation Loc) override {
1822 PartialDiagnosticAt Warning(Loc,
1823 S.PDiag(diag::warn_acquire_requires_negative_cap)
1824 << Kind << LockName << Neg);
1825 Warnings.emplace_back(std::move(Warning), getNotes());
1828 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1829 SourceLocation Loc) override {
1830 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1831 << Kind << FunName << LockName);
1832 Warnings.emplace_back(std::move(Warning), getNotes());
1835 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1836 SourceLocation Loc) override {
1837 PartialDiagnosticAt Warning(Loc,
1838 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1839 Warnings.emplace_back(std::move(Warning), getNotes());
1842 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
1843 PartialDiagnosticAt Warning(Loc,
1844 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1845 Warnings.emplace_back(std::move(Warning), getNotes());
1848 void enterFunction(const FunctionDecl* FD) override {
1849 CurrentFunction = FD;
1852 void leaveFunction(const FunctionDecl* FD) override {
1853 CurrentFunction = nullptr;
1856 } // anonymous namespace
1857 } // namespace threadSafety
1858 } // namespace clang
1860 //===----------------------------------------------------------------------===//
1862 //===----------------------------------------------------------------------===//
1865 namespace consumed {
1867 class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1874 ConsumedWarningsHandler(Sema &S) : S(S) {}
1876 void emitDiagnostics() override {
1877 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1878 for (const auto &Diag : Warnings) {
1879 S.Diag(Diag.first.first, Diag.first.second);
1880 for (const auto &Note : Diag.second)
1881 S.Diag(Note.first, Note.second);
1885 void warnLoopStateMismatch(SourceLocation Loc,
1886 StringRef VariableName) override {
1887 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1890 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1893 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1894 StringRef VariableName,
1895 StringRef ExpectedState,
1896 StringRef ObservedState) override {
1898 PartialDiagnosticAt Warning(Loc, S.PDiag(
1899 diag::warn_param_return_typestate_mismatch) << VariableName <<
1900 ExpectedState << ObservedState);
1902 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1905 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1906 StringRef ObservedState) override {
1908 PartialDiagnosticAt Warning(Loc, S.PDiag(
1909 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1911 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1914 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1915 StringRef TypeName) override {
1916 PartialDiagnosticAt Warning(Loc, S.PDiag(
1917 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1919 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1922 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1923 StringRef ObservedState) override {
1925 PartialDiagnosticAt Warning(Loc, S.PDiag(
1926 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1928 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1931 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1932 SourceLocation Loc) override {
1934 PartialDiagnosticAt Warning(Loc, S.PDiag(
1935 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1937 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1940 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1941 StringRef State, SourceLocation Loc) override {
1943 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1944 MethodName << VariableName << State);
1946 Warnings.emplace_back(std::move(Warning), OptionalNotes());
1949 } // anonymous namespace
1950 } // namespace consumed
1951 } // namespace clang
1953 //===----------------------------------------------------------------------===//
1954 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1955 // warnings on a function, method, or block.
1956 //===----------------------------------------------------------------------===//
1958 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1959 enableCheckFallThrough = 1;
1960 enableCheckUnreachable = 0;
1961 enableThreadSafetyAnalysis = 0;
1962 enableConsumedAnalysis = 0;
1965 static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1966 return (unsigned)!D.isIgnored(diag, SourceLocation());
1969 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1971 NumFunctionsAnalyzed(0),
1972 NumFunctionsWithBadCFGs(0),
1974 MaxCFGBlocksPerFunction(0),
1975 NumUninitAnalysisFunctions(0),
1976 NumUninitAnalysisVariables(0),
1977 MaxUninitAnalysisVariablesPerFunction(0),
1978 NumUninitAnalysisBlockVisits(0),
1979 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1981 using namespace diag;
1982 DiagnosticsEngine &D = S.getDiagnostics();
1984 DefaultPolicy.enableCheckUnreachable =
1985 isEnabled(D, warn_unreachable) ||
1986 isEnabled(D, warn_unreachable_break) ||
1987 isEnabled(D, warn_unreachable_return) ||
1988 isEnabled(D, warn_unreachable_loop_increment);
1990 DefaultPolicy.enableThreadSafetyAnalysis =
1991 isEnabled(D, warn_double_lock);
1993 DefaultPolicy.enableConsumedAnalysis =
1994 isEnabled(D, warn_use_in_invalid_state);
1997 static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1998 for (const auto &D : fscope->PossiblyUnreachableDiags)
1999 S.Diag(D.Loc, D.PD);
2003 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
2004 sema::FunctionScopeInfo *fscope,
2005 const Decl *D, const BlockExpr *blkExpr) {
2007 // We avoid doing analysis-based warnings when there are errors for
2009 // (1) The CFGs often can't be constructed (if the body is invalid), so
2010 // don't bother trying.
2011 // (2) The code already has problems; running the analysis just takes more
2013 DiagnosticsEngine &Diags = S.getDiagnostics();
2015 // Do not do any analysis if we are going to just ignore them.
2016 if (Diags.getIgnoreAllWarnings() ||
2017 (Diags.getSuppressSystemWarnings() &&
2018 S.SourceMgr.isInSystemHeader(D->getLocation())))
2021 // For code in dependent contexts, we'll do this at instantiation time.
2022 if (cast<DeclContext>(D)->isDependentContext())
2025 if (Diags.hasUncompilableErrorOccurred()) {
2026 // Flush out any possibly unreachable diagnostics.
2027 flushDiagnostics(S, fscope);
2031 const Stmt *Body = D->getBody();
2034 // Construct the analysis context with the specified CFG build options.
2035 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
2037 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
2038 // explosion for destructors that can result and the compile time hit.
2039 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2040 AC.getCFGBuildOptions().AddEHEdges = false;
2041 AC.getCFGBuildOptions().AddInitializers = true;
2042 AC.getCFGBuildOptions().AddImplicitDtors = true;
2043 AC.getCFGBuildOptions().AddTemporaryDtors = true;
2044 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2045 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2047 // Force that certain expressions appear as CFGElements in the CFG. This
2048 // is used to speed up various analyses.
2049 // FIXME: This isn't the right factoring. This is here for initial
2050 // prototyping, but we need a way for analyses to say what expressions they
2051 // expect to always be CFGElements and then fill in the BuildOptions
2052 // appropriately. This is essentially a layering violation.
2053 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2054 P.enableConsumedAnalysis) {
2055 // Unreachable code analysis and thread safety require a linearized CFG.
2056 AC.getCFGBuildOptions().setAllAlwaysAdd();
2059 AC.getCFGBuildOptions()
2060 .setAlwaysAdd(Stmt::BinaryOperatorClass)
2061 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
2062 .setAlwaysAdd(Stmt::BlockExprClass)
2063 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2064 .setAlwaysAdd(Stmt::DeclRefExprClass)
2065 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
2066 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2067 .setAlwaysAdd(Stmt::AttributedStmtClass);
2070 // Install the logical handler for -Wtautological-overlap-compare
2071 std::unique_ptr<LogicalErrorHandler> LEH;
2072 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2073 D->getLocStart())) {
2074 LEH.reset(new LogicalErrorHandler(S));
2075 AC.getCFGBuildOptions().Observer = LEH.get();
2078 // Emit delayed diagnostics.
2079 if (!fscope->PossiblyUnreachableDiags.empty()) {
2080 bool analyzed = false;
2082 // Register the expressions with the CFGBuilder.
2083 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2085 AC.registerForcedBlockExpression(D.stmt);
2090 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2091 bool processed = false;
2093 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
2094 CFGReverseBlockReachabilityAnalysis *cra =
2095 AC.getCFGReachablityAnalysis();
2096 // FIXME: We should be able to assert that block is non-null, but
2097 // the CFG analysis can skip potentially-evaluated expressions in
2098 // edge cases; see test/Sema/vla-2.c.
2100 // Can this block be reached from the entrance?
2101 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
2102 S.Diag(D.Loc, D.PD);
2107 // Emit the warning anyway if we cannot map to a basic block.
2108 S.Diag(D.Loc, D.PD);
2114 flushDiagnostics(S, fscope);
2117 // Warning: check missing 'return'
2118 if (P.enableCheckFallThrough) {
2119 const CheckFallThroughDiagnostics &CD =
2121 ? CheckFallThroughDiagnostics::MakeForBlock()
2122 : (isa<CXXMethodDecl>(D) &&
2123 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2124 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2125 ? CheckFallThroughDiagnostics::MakeForLambda()
2126 : (fscope->isCoroutine()
2127 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2128 : CheckFallThroughDiagnostics::MakeForFunction(D)));
2129 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
2132 // Warning: check for unreachable code
2133 if (P.enableCheckUnreachable) {
2134 // Only check for unreachable code on non-template instantiations.
2135 // Different template instantiations can effectively change the control-flow
2136 // and it is very difficult to prove that a snippet of code in a template
2137 // is unreachable for all instantiations.
2138 bool isTemplateInstantiation = false;
2139 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2140 isTemplateInstantiation = Function->isTemplateInstantiation();
2141 if (!isTemplateInstantiation)
2142 CheckUnreachable(S, AC);
2145 // Check for thread safety violations
2146 if (P.enableThreadSafetyAnalysis) {
2147 SourceLocation FL = AC.getDecl()->getLocation();
2148 SourceLocation FEL = AC.getDecl()->getLocEnd();
2149 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
2150 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
2151 Reporter.setIssueBetaWarnings(true);
2152 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2153 Reporter.setVerbose(true);
2155 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2156 &S.ThreadSafetyDeclCache);
2157 Reporter.emitDiagnostics();
2160 // Check for violations of consumed properties.
2161 if (P.enableConsumedAnalysis) {
2162 consumed::ConsumedWarningsHandler WarningHandler(S);
2163 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
2167 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2168 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2169 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
2170 if (CFG *cfg = AC.getCFG()) {
2171 UninitValsDiagReporter reporter(S);
2172 UninitVariablesAnalysisStats stats;
2173 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2174 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2177 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2178 ++NumUninitAnalysisFunctions;
2179 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2180 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2181 MaxUninitAnalysisVariablesPerFunction =
2182 std::max(MaxUninitAnalysisVariablesPerFunction,
2183 stats.NumVariablesAnalyzed);
2184 MaxUninitAnalysisBlockVisitsPerFunction =
2185 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2186 stats.NumBlockVisits);
2191 bool FallThroughDiagFull =
2192 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2193 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2194 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2195 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2196 fscope->HasFallthroughStmt) {
2197 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2200 if (S.getLangOpts().ObjCWeak &&
2201 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2202 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2205 // Check for infinite self-recursion in functions
2206 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2207 D->getLocStart())) {
2208 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2209 checkRecursiveFunction(S, FD, Body, AC);
2213 // Check for throw out of non-throwing function.
2214 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2215 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2216 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2217 checkThrowInNonThrowingFunc(S, FD, AC);
2219 // If none of the previous checks caused a CFG build, trigger one here
2220 // for -Wtautological-overlap-compare
2221 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2222 D->getLocStart())) {
2226 // Collect statistics about the CFG if it was built.
2227 if (S.CollectStats && AC.isCFGBuilt()) {
2228 ++NumFunctionsAnalyzed;
2229 if (CFG *cfg = AC.getCFG()) {
2230 // If we successfully built a CFG for this context, record some more
2231 // detail information about it.
2232 NumCFGBlocks += cfg->getNumBlockIDs();
2233 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2234 cfg->getNumBlockIDs());
2236 ++NumFunctionsWithBadCFGs;
2241 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2242 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2244 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2245 unsigned AvgCFGBlocksPerFunction =
2246 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2247 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2248 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2249 << " " << NumCFGBlocks << " CFG blocks built.\n"
2250 << " " << AvgCFGBlocksPerFunction
2251 << " average CFG blocks per function.\n"
2252 << " " << MaxCFGBlocksPerFunction
2253 << " max CFG blocks per function.\n";
2255 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2256 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2257 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2258 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2259 llvm::errs() << NumUninitAnalysisFunctions
2260 << " functions analyzed for uninitialiazed variables\n"
2261 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2262 << " " << AvgUninitVariablesPerFunction
2263 << " average variables per function.\n"
2264 << " " << MaxUninitAnalysisVariablesPerFunction
2265 << " max variables per function.\n"
2266 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2267 << " " << AvgUninitBlockVisitsPerFunction
2268 << " average block visits per function.\n"
2269 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2270 << " max block visits per function.\n";