xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/AnalysisBasedWarnings.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file defines analysis_warnings::[Policy,Executor].
107330f729Sjoerg // Together they are used by Sema to issue warnings based on inexpensive
117330f729Sjoerg // static analysis algorithms in libAnalysis.
127330f729Sjoerg //
137330f729Sjoerg //===----------------------------------------------------------------------===//
147330f729Sjoerg 
157330f729Sjoerg #include "clang/Sema/AnalysisBasedWarnings.h"
167330f729Sjoerg #include "clang/AST/DeclCXX.h"
177330f729Sjoerg #include "clang/AST/DeclObjC.h"
187330f729Sjoerg #include "clang/AST/EvaluatedExprVisitor.h"
197330f729Sjoerg #include "clang/AST/ExprCXX.h"
207330f729Sjoerg #include "clang/AST/ExprObjC.h"
217330f729Sjoerg #include "clang/AST/ParentMap.h"
227330f729Sjoerg #include "clang/AST/RecursiveASTVisitor.h"
237330f729Sjoerg #include "clang/AST/StmtCXX.h"
247330f729Sjoerg #include "clang/AST/StmtObjC.h"
257330f729Sjoerg #include "clang/AST/StmtVisitor.h"
267330f729Sjoerg #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
27*e038c9c4Sjoerg #include "clang/Analysis/Analyses/CalledOnceCheck.h"
287330f729Sjoerg #include "clang/Analysis/Analyses/Consumed.h"
297330f729Sjoerg #include "clang/Analysis/Analyses/ReachableCode.h"
307330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafety.h"
317330f729Sjoerg #include "clang/Analysis/Analyses/UninitializedValues.h"
327330f729Sjoerg #include "clang/Analysis/AnalysisDeclContext.h"
337330f729Sjoerg #include "clang/Analysis/CFG.h"
347330f729Sjoerg #include "clang/Analysis/CFGStmtMap.h"
357330f729Sjoerg #include "clang/Basic/SourceLocation.h"
367330f729Sjoerg #include "clang/Basic/SourceManager.h"
377330f729Sjoerg #include "clang/Lex/Preprocessor.h"
387330f729Sjoerg #include "clang/Sema/ScopeInfo.h"
397330f729Sjoerg #include "clang/Sema/SemaInternal.h"
40*e038c9c4Sjoerg #include "llvm/ADT/ArrayRef.h"
417330f729Sjoerg #include "llvm/ADT/BitVector.h"
427330f729Sjoerg #include "llvm/ADT/MapVector.h"
437330f729Sjoerg #include "llvm/ADT/SmallString.h"
447330f729Sjoerg #include "llvm/ADT/SmallVector.h"
457330f729Sjoerg #include "llvm/ADT/StringRef.h"
467330f729Sjoerg #include "llvm/Support/Casting.h"
477330f729Sjoerg #include <algorithm>
487330f729Sjoerg #include <deque>
497330f729Sjoerg #include <iterator>
507330f729Sjoerg 
517330f729Sjoerg using namespace clang;
527330f729Sjoerg 
537330f729Sjoerg //===----------------------------------------------------------------------===//
547330f729Sjoerg // Unreachable code analysis.
557330f729Sjoerg //===----------------------------------------------------------------------===//
567330f729Sjoerg 
577330f729Sjoerg namespace {
587330f729Sjoerg   class UnreachableCodeHandler : public reachable_code::Callback {
597330f729Sjoerg     Sema &S;
607330f729Sjoerg     SourceRange PreviousSilenceableCondVal;
617330f729Sjoerg 
627330f729Sjoerg   public:
UnreachableCodeHandler(Sema & s)637330f729Sjoerg     UnreachableCodeHandler(Sema &s) : S(s) {}
647330f729Sjoerg 
HandleUnreachable(reachable_code::UnreachableKind UK,SourceLocation L,SourceRange SilenceableCondVal,SourceRange R1,SourceRange R2)657330f729Sjoerg     void HandleUnreachable(reachable_code::UnreachableKind UK,
667330f729Sjoerg                            SourceLocation L,
677330f729Sjoerg                            SourceRange SilenceableCondVal,
687330f729Sjoerg                            SourceRange R1,
697330f729Sjoerg                            SourceRange R2) override {
707330f729Sjoerg       // Avoid reporting multiple unreachable code diagnostics that are
717330f729Sjoerg       // triggered by the same conditional value.
727330f729Sjoerg       if (PreviousSilenceableCondVal.isValid() &&
737330f729Sjoerg           SilenceableCondVal.isValid() &&
747330f729Sjoerg           PreviousSilenceableCondVal == SilenceableCondVal)
757330f729Sjoerg         return;
767330f729Sjoerg       PreviousSilenceableCondVal = SilenceableCondVal;
777330f729Sjoerg 
787330f729Sjoerg       unsigned diag = diag::warn_unreachable;
797330f729Sjoerg       switch (UK) {
807330f729Sjoerg         case reachable_code::UK_Break:
817330f729Sjoerg           diag = diag::warn_unreachable_break;
827330f729Sjoerg           break;
837330f729Sjoerg         case reachable_code::UK_Return:
847330f729Sjoerg           diag = diag::warn_unreachable_return;
857330f729Sjoerg           break;
867330f729Sjoerg         case reachable_code::UK_Loop_Increment:
877330f729Sjoerg           diag = diag::warn_unreachable_loop_increment;
887330f729Sjoerg           break;
897330f729Sjoerg         case reachable_code::UK_Other:
907330f729Sjoerg           break;
917330f729Sjoerg       }
927330f729Sjoerg 
937330f729Sjoerg       S.Diag(L, diag) << R1 << R2;
947330f729Sjoerg 
957330f729Sjoerg       SourceLocation Open = SilenceableCondVal.getBegin();
967330f729Sjoerg       if (Open.isValid()) {
977330f729Sjoerg         SourceLocation Close = SilenceableCondVal.getEnd();
987330f729Sjoerg         Close = S.getLocForEndOfToken(Close);
997330f729Sjoerg         if (Close.isValid()) {
1007330f729Sjoerg           S.Diag(Open, diag::note_unreachable_silence)
1017330f729Sjoerg             << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
1027330f729Sjoerg             << FixItHint::CreateInsertion(Close, ")");
1037330f729Sjoerg         }
1047330f729Sjoerg       }
1057330f729Sjoerg     }
1067330f729Sjoerg   };
1077330f729Sjoerg } // anonymous namespace
1087330f729Sjoerg 
1097330f729Sjoerg /// CheckUnreachable - Check for unreachable code.
CheckUnreachable(Sema & S,AnalysisDeclContext & AC)1107330f729Sjoerg static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
1117330f729Sjoerg   // As a heuristic prune all diagnostics not in the main file.  Currently
1127330f729Sjoerg   // the majority of warnings in headers are false positives.  These
1137330f729Sjoerg   // are largely caused by configuration state, e.g. preprocessor
1147330f729Sjoerg   // defined code, etc.
1157330f729Sjoerg   //
1167330f729Sjoerg   // Note that this is also a performance optimization.  Analyzing
1177330f729Sjoerg   // headers many times can be expensive.
1187330f729Sjoerg   if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
1197330f729Sjoerg     return;
1207330f729Sjoerg 
1217330f729Sjoerg   UnreachableCodeHandler UC(S);
1227330f729Sjoerg   reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
1237330f729Sjoerg }
1247330f729Sjoerg 
1257330f729Sjoerg namespace {
1267330f729Sjoerg /// Warn on logical operator errors in CFGBuilder
1277330f729Sjoerg class LogicalErrorHandler : public CFGCallback {
1287330f729Sjoerg   Sema &S;
1297330f729Sjoerg 
1307330f729Sjoerg public:
LogicalErrorHandler(Sema & S)1317330f729Sjoerg   LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
1327330f729Sjoerg 
HasMacroID(const Expr * E)1337330f729Sjoerg   static bool HasMacroID(const Expr *E) {
1347330f729Sjoerg     if (E->getExprLoc().isMacroID())
1357330f729Sjoerg       return true;
1367330f729Sjoerg 
1377330f729Sjoerg     // Recurse to children.
1387330f729Sjoerg     for (const Stmt *SubStmt : E->children())
1397330f729Sjoerg       if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
1407330f729Sjoerg         if (HasMacroID(SubExpr))
1417330f729Sjoerg           return true;
1427330f729Sjoerg 
1437330f729Sjoerg     return false;
1447330f729Sjoerg   }
1457330f729Sjoerg 
compareAlwaysTrue(const BinaryOperator * B,bool isAlwaysTrue)1467330f729Sjoerg   void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
1477330f729Sjoerg     if (HasMacroID(B))
1487330f729Sjoerg       return;
1497330f729Sjoerg 
1507330f729Sjoerg     SourceRange DiagRange = B->getSourceRange();
1517330f729Sjoerg     S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
1527330f729Sjoerg         << DiagRange << isAlwaysTrue;
1537330f729Sjoerg   }
1547330f729Sjoerg 
compareBitwiseEquality(const BinaryOperator * B,bool isAlwaysTrue)1557330f729Sjoerg   void compareBitwiseEquality(const BinaryOperator *B,
1567330f729Sjoerg                               bool isAlwaysTrue) override {
1577330f729Sjoerg     if (HasMacroID(B))
1587330f729Sjoerg       return;
1597330f729Sjoerg 
1607330f729Sjoerg     SourceRange DiagRange = B->getSourceRange();
1617330f729Sjoerg     S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
1627330f729Sjoerg         << DiagRange << isAlwaysTrue;
1637330f729Sjoerg   }
1647330f729Sjoerg 
compareBitwiseOr(const BinaryOperator * B)1657330f729Sjoerg   void compareBitwiseOr(const BinaryOperator *B) override {
1667330f729Sjoerg     if (HasMacroID(B))
1677330f729Sjoerg       return;
1687330f729Sjoerg 
1697330f729Sjoerg     SourceRange DiagRange = B->getSourceRange();
1707330f729Sjoerg     S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_or) << DiagRange;
1717330f729Sjoerg   }
1727330f729Sjoerg 
hasActiveDiagnostics(DiagnosticsEngine & Diags,SourceLocation Loc)1737330f729Sjoerg   static bool hasActiveDiagnostics(DiagnosticsEngine &Diags,
1747330f729Sjoerg                                    SourceLocation Loc) {
1757330f729Sjoerg     return !Diags.isIgnored(diag::warn_tautological_overlap_comparison, Loc) ||
1767330f729Sjoerg            !Diags.isIgnored(diag::warn_comparison_bitwise_or, Loc);
1777330f729Sjoerg   }
1787330f729Sjoerg };
1797330f729Sjoerg } // anonymous namespace
1807330f729Sjoerg 
1817330f729Sjoerg //===----------------------------------------------------------------------===//
1827330f729Sjoerg // Check for infinite self-recursion in functions
1837330f729Sjoerg //===----------------------------------------------------------------------===//
1847330f729Sjoerg 
1857330f729Sjoerg // Returns true if the function is called anywhere within the CFGBlock.
1867330f729Sjoerg // For member functions, the additional condition of being call from the
1877330f729Sjoerg // this pointer is required.
hasRecursiveCallInPath(const FunctionDecl * FD,CFGBlock & Block)1887330f729Sjoerg static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
1897330f729Sjoerg   // Process all the Stmt's in this block to find any calls to FD.
1907330f729Sjoerg   for (const auto &B : Block) {
1917330f729Sjoerg     if (B.getKind() != CFGElement::Statement)
1927330f729Sjoerg       continue;
1937330f729Sjoerg 
1947330f729Sjoerg     const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
1957330f729Sjoerg     if (!CE || !CE->getCalleeDecl() ||
1967330f729Sjoerg         CE->getCalleeDecl()->getCanonicalDecl() != FD)
1977330f729Sjoerg       continue;
1987330f729Sjoerg 
1997330f729Sjoerg     // Skip function calls which are qualified with a templated class.
2007330f729Sjoerg     if (const DeclRefExpr *DRE =
2017330f729Sjoerg             dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
2027330f729Sjoerg       if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
2037330f729Sjoerg         if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
2047330f729Sjoerg             isa<TemplateSpecializationType>(NNS->getAsType())) {
2057330f729Sjoerg           continue;
2067330f729Sjoerg         }
2077330f729Sjoerg       }
2087330f729Sjoerg     }
2097330f729Sjoerg 
2107330f729Sjoerg     const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
2117330f729Sjoerg     if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
2127330f729Sjoerg         !MCE->getMethodDecl()->isVirtual())
2137330f729Sjoerg       return true;
2147330f729Sjoerg   }
2157330f729Sjoerg   return false;
2167330f729Sjoerg }
2177330f729Sjoerg 
2187330f729Sjoerg // Returns true if every path from the entry block passes through a call to FD.
checkForRecursiveFunctionCall(const FunctionDecl * FD,CFG * cfg)2197330f729Sjoerg static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
2207330f729Sjoerg   llvm::SmallPtrSet<CFGBlock *, 16> Visited;
2217330f729Sjoerg   llvm::SmallVector<CFGBlock *, 16> WorkList;
2227330f729Sjoerg   // Keep track of whether we found at least one recursive path.
2237330f729Sjoerg   bool foundRecursion = false;
2247330f729Sjoerg 
2257330f729Sjoerg   const unsigned ExitID = cfg->getExit().getBlockID();
2267330f729Sjoerg 
2277330f729Sjoerg   // Seed the work list with the entry block.
2287330f729Sjoerg   WorkList.push_back(&cfg->getEntry());
2297330f729Sjoerg 
2307330f729Sjoerg   while (!WorkList.empty()) {
2317330f729Sjoerg     CFGBlock *Block = WorkList.pop_back_val();
2327330f729Sjoerg 
2337330f729Sjoerg     for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
2347330f729Sjoerg       if (CFGBlock *SuccBlock = *I) {
2357330f729Sjoerg         if (!Visited.insert(SuccBlock).second)
2367330f729Sjoerg           continue;
2377330f729Sjoerg 
2387330f729Sjoerg         // Found a path to the exit node without a recursive call.
2397330f729Sjoerg         if (ExitID == SuccBlock->getBlockID())
2407330f729Sjoerg           return false;
2417330f729Sjoerg 
2427330f729Sjoerg         // If the successor block contains a recursive call, end analysis there.
2437330f729Sjoerg         if (hasRecursiveCallInPath(FD, *SuccBlock)) {
2447330f729Sjoerg           foundRecursion = true;
2457330f729Sjoerg           continue;
2467330f729Sjoerg         }
2477330f729Sjoerg 
2487330f729Sjoerg         WorkList.push_back(SuccBlock);
2497330f729Sjoerg       }
2507330f729Sjoerg     }
2517330f729Sjoerg   }
2527330f729Sjoerg   return foundRecursion;
2537330f729Sjoerg }
2547330f729Sjoerg 
checkRecursiveFunction(Sema & S,const FunctionDecl * FD,const Stmt * Body,AnalysisDeclContext & AC)2557330f729Sjoerg static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
2567330f729Sjoerg                                    const Stmt *Body, AnalysisDeclContext &AC) {
2577330f729Sjoerg   FD = FD->getCanonicalDecl();
2587330f729Sjoerg 
2597330f729Sjoerg   // Only run on non-templated functions and non-templated members of
2607330f729Sjoerg   // templated classes.
2617330f729Sjoerg   if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
2627330f729Sjoerg       FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
2637330f729Sjoerg     return;
2647330f729Sjoerg 
2657330f729Sjoerg   CFG *cfg = AC.getCFG();
2667330f729Sjoerg   if (!cfg) return;
2677330f729Sjoerg 
2687330f729Sjoerg   // If the exit block is unreachable, skip processing the function.
2697330f729Sjoerg   if (cfg->getExit().pred_empty())
2707330f729Sjoerg     return;
2717330f729Sjoerg 
2727330f729Sjoerg   // Emit diagnostic if a recursive function call is detected for all paths.
2737330f729Sjoerg   if (checkForRecursiveFunctionCall(FD, cfg))
2747330f729Sjoerg     S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
2757330f729Sjoerg }
2767330f729Sjoerg 
2777330f729Sjoerg //===----------------------------------------------------------------------===//
2787330f729Sjoerg // Check for throw in a non-throwing function.
2797330f729Sjoerg //===----------------------------------------------------------------------===//
2807330f729Sjoerg 
2817330f729Sjoerg /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
2827330f729Sjoerg /// can reach ExitBlock.
throwEscapes(Sema & S,const CXXThrowExpr * E,CFGBlock & ThrowBlock,CFG * Body)2837330f729Sjoerg static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
2847330f729Sjoerg                          CFG *Body) {
2857330f729Sjoerg   SmallVector<CFGBlock *, 16> Stack;
2867330f729Sjoerg   llvm::BitVector Queued(Body->getNumBlockIDs());
2877330f729Sjoerg 
2887330f729Sjoerg   Stack.push_back(&ThrowBlock);
2897330f729Sjoerg   Queued[ThrowBlock.getBlockID()] = true;
2907330f729Sjoerg 
2917330f729Sjoerg   while (!Stack.empty()) {
2927330f729Sjoerg     CFGBlock &UnwindBlock = *Stack.back();
2937330f729Sjoerg     Stack.pop_back();
2947330f729Sjoerg 
2957330f729Sjoerg     for (auto &Succ : UnwindBlock.succs()) {
2967330f729Sjoerg       if (!Succ.isReachable() || Queued[Succ->getBlockID()])
2977330f729Sjoerg         continue;
2987330f729Sjoerg 
2997330f729Sjoerg       if (Succ->getBlockID() == Body->getExit().getBlockID())
3007330f729Sjoerg         return true;
3017330f729Sjoerg 
3027330f729Sjoerg       if (auto *Catch =
3037330f729Sjoerg               dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
3047330f729Sjoerg         QualType Caught = Catch->getCaughtType();
3057330f729Sjoerg         if (Caught.isNull() || // catch (...) catches everything
3067330f729Sjoerg             !E->getSubExpr() || // throw; is considered cuaght by any handler
3077330f729Sjoerg             S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
3087330f729Sjoerg           // Exception doesn't escape via this path.
3097330f729Sjoerg           break;
3107330f729Sjoerg       } else {
3117330f729Sjoerg         Stack.push_back(Succ);
3127330f729Sjoerg         Queued[Succ->getBlockID()] = true;
3137330f729Sjoerg       }
3147330f729Sjoerg     }
3157330f729Sjoerg   }
3167330f729Sjoerg 
3177330f729Sjoerg   return false;
3187330f729Sjoerg }
3197330f729Sjoerg 
visitReachableThrows(CFG * BodyCFG,llvm::function_ref<void (const CXXThrowExpr *,CFGBlock &)> Visit)3207330f729Sjoerg static void visitReachableThrows(
3217330f729Sjoerg     CFG *BodyCFG,
3227330f729Sjoerg     llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
3237330f729Sjoerg   llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
3247330f729Sjoerg   clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
3257330f729Sjoerg   for (CFGBlock *B : *BodyCFG) {
3267330f729Sjoerg     if (!Reachable[B->getBlockID()])
3277330f729Sjoerg       continue;
3287330f729Sjoerg     for (CFGElement &E : *B) {
3297330f729Sjoerg       Optional<CFGStmt> S = E.getAs<CFGStmt>();
3307330f729Sjoerg       if (!S)
3317330f729Sjoerg         continue;
3327330f729Sjoerg       if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
3337330f729Sjoerg         Visit(Throw, *B);
3347330f729Sjoerg     }
3357330f729Sjoerg   }
3367330f729Sjoerg }
3377330f729Sjoerg 
EmitDiagForCXXThrowInNonThrowingFunc(Sema & S,SourceLocation OpLoc,const FunctionDecl * FD)3387330f729Sjoerg static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
3397330f729Sjoerg                                                  const FunctionDecl *FD) {
3407330f729Sjoerg   if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
3417330f729Sjoerg       FD->getTypeSourceInfo()) {
3427330f729Sjoerg     S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
3437330f729Sjoerg     if (S.getLangOpts().CPlusPlus11 &&
3447330f729Sjoerg         (isa<CXXDestructorDecl>(FD) ||
3457330f729Sjoerg          FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3467330f729Sjoerg          FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
3477330f729Sjoerg       if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
3487330f729Sjoerg                                          getAs<FunctionProtoType>())
3497330f729Sjoerg         S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
3507330f729Sjoerg             << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
3517330f729Sjoerg             << FD->getExceptionSpecSourceRange();
3527330f729Sjoerg     } else
3537330f729Sjoerg       S.Diag(FD->getLocation(), diag::note_throw_in_function)
3547330f729Sjoerg           << FD->getExceptionSpecSourceRange();
3557330f729Sjoerg   }
3567330f729Sjoerg }
3577330f729Sjoerg 
checkThrowInNonThrowingFunc(Sema & S,const FunctionDecl * FD,AnalysisDeclContext & AC)3587330f729Sjoerg static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
3597330f729Sjoerg                                         AnalysisDeclContext &AC) {
3607330f729Sjoerg   CFG *BodyCFG = AC.getCFG();
3617330f729Sjoerg   if (!BodyCFG)
3627330f729Sjoerg     return;
3637330f729Sjoerg   if (BodyCFG->getExit().pred_empty())
3647330f729Sjoerg     return;
3657330f729Sjoerg   visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
3667330f729Sjoerg     if (throwEscapes(S, Throw, Block, BodyCFG))
3677330f729Sjoerg       EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
3687330f729Sjoerg   });
3697330f729Sjoerg }
3707330f729Sjoerg 
isNoexcept(const FunctionDecl * FD)3717330f729Sjoerg static bool isNoexcept(const FunctionDecl *FD) {
3727330f729Sjoerg   const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
3737330f729Sjoerg   if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
3747330f729Sjoerg     return true;
3757330f729Sjoerg   return false;
3767330f729Sjoerg }
3777330f729Sjoerg 
3787330f729Sjoerg //===----------------------------------------------------------------------===//
3797330f729Sjoerg // Check for missing return value.
3807330f729Sjoerg //===----------------------------------------------------------------------===//
3817330f729Sjoerg 
3827330f729Sjoerg enum ControlFlowKind {
3837330f729Sjoerg   UnknownFallThrough,
3847330f729Sjoerg   NeverFallThrough,
3857330f729Sjoerg   MaybeFallThrough,
3867330f729Sjoerg   AlwaysFallThrough,
3877330f729Sjoerg   NeverFallThroughOrReturn
3887330f729Sjoerg };
3897330f729Sjoerg 
3907330f729Sjoerg /// CheckFallThrough - Check that we don't fall off the end of a
3917330f729Sjoerg /// Statement that should return a value.
3927330f729Sjoerg ///
3937330f729Sjoerg /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
3947330f729Sjoerg /// MaybeFallThrough iff we might or might not fall off the end,
3957330f729Sjoerg /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
3967330f729Sjoerg /// return.  We assume NeverFallThrough iff we never fall off the end of the
3977330f729Sjoerg /// statement but we may return.  We assume that functions not marked noreturn
3987330f729Sjoerg /// will return.
CheckFallThrough(AnalysisDeclContext & AC)3997330f729Sjoerg static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
4007330f729Sjoerg   CFG *cfg = AC.getCFG();
4017330f729Sjoerg   if (!cfg) return UnknownFallThrough;
4027330f729Sjoerg 
4037330f729Sjoerg   // The CFG leaves in dead things, and we don't want the dead code paths to
4047330f729Sjoerg   // confuse us, so we mark all live things first.
4057330f729Sjoerg   llvm::BitVector live(cfg->getNumBlockIDs());
4067330f729Sjoerg   unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
4077330f729Sjoerg                                                           live);
4087330f729Sjoerg 
4097330f729Sjoerg   bool AddEHEdges = AC.getAddEHEdges();
4107330f729Sjoerg   if (!AddEHEdges && count != cfg->getNumBlockIDs())
4117330f729Sjoerg     // When there are things remaining dead, and we didn't add EH edges
4127330f729Sjoerg     // from CallExprs to the catch clauses, we have to go back and
4137330f729Sjoerg     // mark them as live.
4147330f729Sjoerg     for (const auto *B : *cfg) {
4157330f729Sjoerg       if (!live[B->getBlockID()]) {
4167330f729Sjoerg         if (B->pred_begin() == B->pred_end()) {
4177330f729Sjoerg           const Stmt *Term = B->getTerminatorStmt();
4187330f729Sjoerg           if (Term && isa<CXXTryStmt>(Term))
4197330f729Sjoerg             // When not adding EH edges from calls, catch clauses
4207330f729Sjoerg             // can otherwise seem dead.  Avoid noting them as dead.
4217330f729Sjoerg             count += reachable_code::ScanReachableFromBlock(B, live);
4227330f729Sjoerg           continue;
4237330f729Sjoerg         }
4247330f729Sjoerg       }
4257330f729Sjoerg     }
4267330f729Sjoerg 
4277330f729Sjoerg   // Now we know what is live, we check the live precessors of the exit block
4287330f729Sjoerg   // and look for fall through paths, being careful to ignore normal returns,
4297330f729Sjoerg   // and exceptional paths.
4307330f729Sjoerg   bool HasLiveReturn = false;
4317330f729Sjoerg   bool HasFakeEdge = false;
4327330f729Sjoerg   bool HasPlainEdge = false;
4337330f729Sjoerg   bool HasAbnormalEdge = false;
4347330f729Sjoerg 
4357330f729Sjoerg   // Ignore default cases that aren't likely to be reachable because all
4367330f729Sjoerg   // enums in a switch(X) have explicit case statements.
4377330f729Sjoerg   CFGBlock::FilterOptions FO;
4387330f729Sjoerg   FO.IgnoreDefaultsWithCoveredEnums = 1;
4397330f729Sjoerg 
4407330f729Sjoerg   for (CFGBlock::filtered_pred_iterator I =
4417330f729Sjoerg            cfg->getExit().filtered_pred_start_end(FO);
4427330f729Sjoerg        I.hasMore(); ++I) {
4437330f729Sjoerg     const CFGBlock &B = **I;
4447330f729Sjoerg     if (!live[B.getBlockID()])
4457330f729Sjoerg       continue;
4467330f729Sjoerg 
4477330f729Sjoerg     // Skip blocks which contain an element marked as no-return. They don't
4487330f729Sjoerg     // represent actually viable edges into the exit block, so mark them as
4497330f729Sjoerg     // abnormal.
4507330f729Sjoerg     if (B.hasNoReturnElement()) {
4517330f729Sjoerg       HasAbnormalEdge = true;
4527330f729Sjoerg       continue;
4537330f729Sjoerg     }
4547330f729Sjoerg 
4557330f729Sjoerg     // Destructors can appear after the 'return' in the CFG.  This is
4567330f729Sjoerg     // normal.  We need to look pass the destructors for the return
4577330f729Sjoerg     // statement (if it exists).
4587330f729Sjoerg     CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
4597330f729Sjoerg 
4607330f729Sjoerg     for ( ; ri != re ; ++ri)
4617330f729Sjoerg       if (ri->getAs<CFGStmt>())
4627330f729Sjoerg         break;
4637330f729Sjoerg 
4647330f729Sjoerg     // No more CFGElements in the block?
4657330f729Sjoerg     if (ri == re) {
4667330f729Sjoerg       const Stmt *Term = B.getTerminatorStmt();
4677330f729Sjoerg       if (Term && isa<CXXTryStmt>(Term)) {
4687330f729Sjoerg         HasAbnormalEdge = true;
4697330f729Sjoerg         continue;
4707330f729Sjoerg       }
4717330f729Sjoerg       // A labeled empty statement, or the entry block...
4727330f729Sjoerg       HasPlainEdge = true;
4737330f729Sjoerg       continue;
4747330f729Sjoerg     }
4757330f729Sjoerg 
4767330f729Sjoerg     CFGStmt CS = ri->castAs<CFGStmt>();
4777330f729Sjoerg     const Stmt *S = CS.getStmt();
4787330f729Sjoerg     if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
4797330f729Sjoerg       HasLiveReturn = true;
4807330f729Sjoerg       continue;
4817330f729Sjoerg     }
4827330f729Sjoerg     if (isa<ObjCAtThrowStmt>(S)) {
4837330f729Sjoerg       HasFakeEdge = true;
4847330f729Sjoerg       continue;
4857330f729Sjoerg     }
4867330f729Sjoerg     if (isa<CXXThrowExpr>(S)) {
4877330f729Sjoerg       HasFakeEdge = true;
4887330f729Sjoerg       continue;
4897330f729Sjoerg     }
4907330f729Sjoerg     if (isa<MSAsmStmt>(S)) {
4917330f729Sjoerg       // TODO: Verify this is correct.
4927330f729Sjoerg       HasFakeEdge = true;
4937330f729Sjoerg       HasLiveReturn = true;
4947330f729Sjoerg       continue;
4957330f729Sjoerg     }
4967330f729Sjoerg     if (isa<CXXTryStmt>(S)) {
4977330f729Sjoerg       HasAbnormalEdge = true;
4987330f729Sjoerg       continue;
4997330f729Sjoerg     }
5007330f729Sjoerg     if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
5017330f729Sjoerg         == B.succ_end()) {
5027330f729Sjoerg       HasAbnormalEdge = true;
5037330f729Sjoerg       continue;
5047330f729Sjoerg     }
5057330f729Sjoerg 
5067330f729Sjoerg     HasPlainEdge = true;
5077330f729Sjoerg   }
5087330f729Sjoerg   if (!HasPlainEdge) {
5097330f729Sjoerg     if (HasLiveReturn)
5107330f729Sjoerg       return NeverFallThrough;
5117330f729Sjoerg     return NeverFallThroughOrReturn;
5127330f729Sjoerg   }
5137330f729Sjoerg   if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
5147330f729Sjoerg     return MaybeFallThrough;
5157330f729Sjoerg   // This says AlwaysFallThrough for calls to functions that are not marked
5167330f729Sjoerg   // noreturn, that don't return.  If people would like this warning to be more
5177330f729Sjoerg   // accurate, such functions should be marked as noreturn.
5187330f729Sjoerg   return AlwaysFallThrough;
5197330f729Sjoerg }
5207330f729Sjoerg 
5217330f729Sjoerg namespace {
5227330f729Sjoerg 
5237330f729Sjoerg struct CheckFallThroughDiagnostics {
5247330f729Sjoerg   unsigned diag_MaybeFallThrough_HasNoReturn;
5257330f729Sjoerg   unsigned diag_MaybeFallThrough_ReturnsNonVoid;
5267330f729Sjoerg   unsigned diag_AlwaysFallThrough_HasNoReturn;
5277330f729Sjoerg   unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
5287330f729Sjoerg   unsigned diag_NeverFallThroughOrReturn;
5297330f729Sjoerg   enum { Function, Block, Lambda, Coroutine } funMode;
5307330f729Sjoerg   SourceLocation FuncLoc;
5317330f729Sjoerg 
MakeForFunction__anondf82a8a60411::CheckFallThroughDiagnostics5327330f729Sjoerg   static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
5337330f729Sjoerg     CheckFallThroughDiagnostics D;
5347330f729Sjoerg     D.FuncLoc = Func->getLocation();
5357330f729Sjoerg     D.diag_MaybeFallThrough_HasNoReturn =
5367330f729Sjoerg       diag::warn_falloff_noreturn_function;
5377330f729Sjoerg     D.diag_MaybeFallThrough_ReturnsNonVoid =
5387330f729Sjoerg       diag::warn_maybe_falloff_nonvoid_function;
5397330f729Sjoerg     D.diag_AlwaysFallThrough_HasNoReturn =
5407330f729Sjoerg       diag::warn_falloff_noreturn_function;
5417330f729Sjoerg     D.diag_AlwaysFallThrough_ReturnsNonVoid =
5427330f729Sjoerg       diag::warn_falloff_nonvoid_function;
5437330f729Sjoerg 
5447330f729Sjoerg     // Don't suggest that virtual functions be marked "noreturn", since they
5457330f729Sjoerg     // might be overridden by non-noreturn functions.
5467330f729Sjoerg     bool isVirtualMethod = false;
5477330f729Sjoerg     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
5487330f729Sjoerg       isVirtualMethod = Method->isVirtual();
5497330f729Sjoerg 
5507330f729Sjoerg     // Don't suggest that template instantiations be marked "noreturn"
5517330f729Sjoerg     bool isTemplateInstantiation = false;
5527330f729Sjoerg     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
5537330f729Sjoerg       isTemplateInstantiation = Function->isTemplateInstantiation();
5547330f729Sjoerg 
5557330f729Sjoerg     if (!isVirtualMethod && !isTemplateInstantiation)
5567330f729Sjoerg       D.diag_NeverFallThroughOrReturn =
5577330f729Sjoerg         diag::warn_suggest_noreturn_function;
5587330f729Sjoerg     else
5597330f729Sjoerg       D.diag_NeverFallThroughOrReturn = 0;
5607330f729Sjoerg 
5617330f729Sjoerg     D.funMode = Function;
5627330f729Sjoerg     return D;
5637330f729Sjoerg   }
5647330f729Sjoerg 
MakeForCoroutine__anondf82a8a60411::CheckFallThroughDiagnostics5657330f729Sjoerg   static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
5667330f729Sjoerg     CheckFallThroughDiagnostics D;
5677330f729Sjoerg     D.FuncLoc = Func->getLocation();
5687330f729Sjoerg     D.diag_MaybeFallThrough_HasNoReturn = 0;
5697330f729Sjoerg     D.diag_MaybeFallThrough_ReturnsNonVoid =
5707330f729Sjoerg         diag::warn_maybe_falloff_nonvoid_coroutine;
5717330f729Sjoerg     D.diag_AlwaysFallThrough_HasNoReturn = 0;
5727330f729Sjoerg     D.diag_AlwaysFallThrough_ReturnsNonVoid =
5737330f729Sjoerg         diag::warn_falloff_nonvoid_coroutine;
5747330f729Sjoerg     D.funMode = Coroutine;
5757330f729Sjoerg     return D;
5767330f729Sjoerg   }
5777330f729Sjoerg 
MakeForBlock__anondf82a8a60411::CheckFallThroughDiagnostics5787330f729Sjoerg   static CheckFallThroughDiagnostics MakeForBlock() {
5797330f729Sjoerg     CheckFallThroughDiagnostics D;
5807330f729Sjoerg     D.diag_MaybeFallThrough_HasNoReturn =
5817330f729Sjoerg       diag::err_noreturn_block_has_return_expr;
5827330f729Sjoerg     D.diag_MaybeFallThrough_ReturnsNonVoid =
5837330f729Sjoerg       diag::err_maybe_falloff_nonvoid_block;
5847330f729Sjoerg     D.diag_AlwaysFallThrough_HasNoReturn =
5857330f729Sjoerg       diag::err_noreturn_block_has_return_expr;
5867330f729Sjoerg     D.diag_AlwaysFallThrough_ReturnsNonVoid =
5877330f729Sjoerg       diag::err_falloff_nonvoid_block;
5887330f729Sjoerg     D.diag_NeverFallThroughOrReturn = 0;
5897330f729Sjoerg     D.funMode = Block;
5907330f729Sjoerg     return D;
5917330f729Sjoerg   }
5927330f729Sjoerg 
MakeForLambda__anondf82a8a60411::CheckFallThroughDiagnostics5937330f729Sjoerg   static CheckFallThroughDiagnostics MakeForLambda() {
5947330f729Sjoerg     CheckFallThroughDiagnostics D;
5957330f729Sjoerg     D.diag_MaybeFallThrough_HasNoReturn =
5967330f729Sjoerg       diag::err_noreturn_lambda_has_return_expr;
5977330f729Sjoerg     D.diag_MaybeFallThrough_ReturnsNonVoid =
5987330f729Sjoerg       diag::warn_maybe_falloff_nonvoid_lambda;
5997330f729Sjoerg     D.diag_AlwaysFallThrough_HasNoReturn =
6007330f729Sjoerg       diag::err_noreturn_lambda_has_return_expr;
6017330f729Sjoerg     D.diag_AlwaysFallThrough_ReturnsNonVoid =
6027330f729Sjoerg       diag::warn_falloff_nonvoid_lambda;
6037330f729Sjoerg     D.diag_NeverFallThroughOrReturn = 0;
6047330f729Sjoerg     D.funMode = Lambda;
6057330f729Sjoerg     return D;
6067330f729Sjoerg   }
6077330f729Sjoerg 
checkDiagnostics__anondf82a8a60411::CheckFallThroughDiagnostics6087330f729Sjoerg   bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
6097330f729Sjoerg                         bool HasNoReturn) const {
6107330f729Sjoerg     if (funMode == Function) {
6117330f729Sjoerg       return (ReturnsVoid ||
6127330f729Sjoerg               D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
6137330f729Sjoerg                           FuncLoc)) &&
6147330f729Sjoerg              (!HasNoReturn ||
6157330f729Sjoerg               D.isIgnored(diag::warn_noreturn_function_has_return_expr,
6167330f729Sjoerg                           FuncLoc)) &&
6177330f729Sjoerg              (!ReturnsVoid ||
6187330f729Sjoerg               D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
6197330f729Sjoerg     }
6207330f729Sjoerg     if (funMode == Coroutine) {
6217330f729Sjoerg       return (ReturnsVoid ||
6227330f729Sjoerg               D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
6237330f729Sjoerg               D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
6247330f729Sjoerg                           FuncLoc)) &&
6257330f729Sjoerg              (!HasNoReturn);
6267330f729Sjoerg     }
6277330f729Sjoerg     // For blocks / lambdas.
6287330f729Sjoerg     return ReturnsVoid && !HasNoReturn;
6297330f729Sjoerg   }
6307330f729Sjoerg };
6317330f729Sjoerg 
6327330f729Sjoerg } // anonymous namespace
6337330f729Sjoerg 
6347330f729Sjoerg /// CheckFallThroughForBody - Check that we don't fall off the end of a
6357330f729Sjoerg /// function that should return a value.  Check that we don't fall off the end
6367330f729Sjoerg /// of a noreturn function.  We assume that functions and blocks not marked
6377330f729Sjoerg /// noreturn will return.
CheckFallThroughForBody(Sema & S,const Decl * D,const Stmt * Body,QualType BlockType,const CheckFallThroughDiagnostics & CD,AnalysisDeclContext & AC,sema::FunctionScopeInfo * FSI)6387330f729Sjoerg static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
6397330f729Sjoerg                                     QualType BlockType,
6407330f729Sjoerg                                     const CheckFallThroughDiagnostics &CD,
6417330f729Sjoerg                                     AnalysisDeclContext &AC,
6427330f729Sjoerg                                     sema::FunctionScopeInfo *FSI) {
6437330f729Sjoerg 
6447330f729Sjoerg   bool ReturnsVoid = false;
6457330f729Sjoerg   bool HasNoReturn = false;
6467330f729Sjoerg   bool IsCoroutine = FSI->isCoroutine();
6477330f729Sjoerg 
6487330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6497330f729Sjoerg     if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
6507330f729Sjoerg       ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
6517330f729Sjoerg     else
6527330f729Sjoerg       ReturnsVoid = FD->getReturnType()->isVoidType();
6537330f729Sjoerg     HasNoReturn = FD->isNoReturn();
6547330f729Sjoerg   }
6557330f729Sjoerg   else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
6567330f729Sjoerg     ReturnsVoid = MD->getReturnType()->isVoidType();
6577330f729Sjoerg     HasNoReturn = MD->hasAttr<NoReturnAttr>();
6587330f729Sjoerg   }
6597330f729Sjoerg   else if (isa<BlockDecl>(D)) {
6607330f729Sjoerg     if (const FunctionType *FT =
6617330f729Sjoerg           BlockType->getPointeeType()->getAs<FunctionType>()) {
6627330f729Sjoerg       if (FT->getReturnType()->isVoidType())
6637330f729Sjoerg         ReturnsVoid = true;
6647330f729Sjoerg       if (FT->getNoReturnAttr())
6657330f729Sjoerg         HasNoReturn = true;
6667330f729Sjoerg     }
6677330f729Sjoerg   }
6687330f729Sjoerg 
6697330f729Sjoerg   DiagnosticsEngine &Diags = S.getDiagnostics();
6707330f729Sjoerg 
6717330f729Sjoerg   // Short circuit for compilation speed.
6727330f729Sjoerg   if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
6737330f729Sjoerg       return;
6747330f729Sjoerg   SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
6757330f729Sjoerg   auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
6767330f729Sjoerg     if (IsCoroutine)
6777330f729Sjoerg       S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
6787330f729Sjoerg     else
6797330f729Sjoerg       S.Diag(Loc, DiagID);
6807330f729Sjoerg   };
6817330f729Sjoerg 
6827330f729Sjoerg   // cpu_dispatch functions permit empty function bodies for ICC compatibility.
6837330f729Sjoerg   if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
6847330f729Sjoerg     return;
6857330f729Sjoerg 
6867330f729Sjoerg   // Either in a function body compound statement, or a function-try-block.
6877330f729Sjoerg   switch (CheckFallThrough(AC)) {
6887330f729Sjoerg     case UnknownFallThrough:
6897330f729Sjoerg       break;
6907330f729Sjoerg 
6917330f729Sjoerg     case MaybeFallThrough:
6927330f729Sjoerg       if (HasNoReturn)
6937330f729Sjoerg         EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
6947330f729Sjoerg       else if (!ReturnsVoid)
6957330f729Sjoerg         EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
6967330f729Sjoerg       break;
6977330f729Sjoerg     case AlwaysFallThrough:
6987330f729Sjoerg       if (HasNoReturn)
6997330f729Sjoerg         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
7007330f729Sjoerg       else if (!ReturnsVoid)
7017330f729Sjoerg         EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
7027330f729Sjoerg       break;
7037330f729Sjoerg     case NeverFallThroughOrReturn:
7047330f729Sjoerg       if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
7057330f729Sjoerg         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7067330f729Sjoerg           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
7077330f729Sjoerg         } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
7087330f729Sjoerg           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
7097330f729Sjoerg         } else {
7107330f729Sjoerg           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
7117330f729Sjoerg         }
7127330f729Sjoerg       }
7137330f729Sjoerg       break;
7147330f729Sjoerg     case NeverFallThrough:
7157330f729Sjoerg       break;
7167330f729Sjoerg   }
7177330f729Sjoerg }
7187330f729Sjoerg 
7197330f729Sjoerg //===----------------------------------------------------------------------===//
7207330f729Sjoerg // -Wuninitialized
7217330f729Sjoerg //===----------------------------------------------------------------------===//
7227330f729Sjoerg 
7237330f729Sjoerg namespace {
7247330f729Sjoerg /// ContainsReference - A visitor class to search for references to
7257330f729Sjoerg /// a particular declaration (the needle) within any evaluated component of an
7267330f729Sjoerg /// expression (recursively).
7277330f729Sjoerg class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
7287330f729Sjoerg   bool FoundReference;
7297330f729Sjoerg   const DeclRefExpr *Needle;
7307330f729Sjoerg 
7317330f729Sjoerg public:
7327330f729Sjoerg   typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
7337330f729Sjoerg 
ContainsReference(ASTContext & Context,const DeclRefExpr * Needle)7347330f729Sjoerg   ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
7357330f729Sjoerg     : Inherited(Context), FoundReference(false), Needle(Needle) {}
7367330f729Sjoerg 
VisitExpr(const Expr * E)7377330f729Sjoerg   void VisitExpr(const Expr *E) {
7387330f729Sjoerg     // Stop evaluating if we already have a reference.
7397330f729Sjoerg     if (FoundReference)
7407330f729Sjoerg       return;
7417330f729Sjoerg 
7427330f729Sjoerg     Inherited::VisitExpr(E);
7437330f729Sjoerg   }
7447330f729Sjoerg 
VisitDeclRefExpr(const DeclRefExpr * E)7457330f729Sjoerg   void VisitDeclRefExpr(const DeclRefExpr *E) {
7467330f729Sjoerg     if (E == Needle)
7477330f729Sjoerg       FoundReference = true;
7487330f729Sjoerg     else
7497330f729Sjoerg       Inherited::VisitDeclRefExpr(E);
7507330f729Sjoerg   }
7517330f729Sjoerg 
doesContainReference() const7527330f729Sjoerg   bool doesContainReference() const { return FoundReference; }
7537330f729Sjoerg };
7547330f729Sjoerg } // anonymous namespace
7557330f729Sjoerg 
SuggestInitializationFixit(Sema & S,const VarDecl * VD)7567330f729Sjoerg static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
7577330f729Sjoerg   QualType VariableTy = VD->getType().getCanonicalType();
7587330f729Sjoerg   if (VariableTy->isBlockPointerType() &&
7597330f729Sjoerg       !VD->hasAttr<BlocksAttr>()) {
7607330f729Sjoerg     S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
7617330f729Sjoerg         << VD->getDeclName()
7627330f729Sjoerg         << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
7637330f729Sjoerg     return true;
7647330f729Sjoerg   }
7657330f729Sjoerg 
7667330f729Sjoerg   // Don't issue a fixit if there is already an initializer.
7677330f729Sjoerg   if (VD->getInit())
7687330f729Sjoerg     return false;
7697330f729Sjoerg 
7707330f729Sjoerg   // Don't suggest a fixit inside macros.
7717330f729Sjoerg   if (VD->getEndLoc().isMacroID())
7727330f729Sjoerg     return false;
7737330f729Sjoerg 
7747330f729Sjoerg   SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
7757330f729Sjoerg 
7767330f729Sjoerg   // Suggest possible initialization (if any).
7777330f729Sjoerg   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
7787330f729Sjoerg   if (Init.empty())
7797330f729Sjoerg     return false;
7807330f729Sjoerg 
7817330f729Sjoerg   S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
7827330f729Sjoerg     << FixItHint::CreateInsertion(Loc, Init);
7837330f729Sjoerg   return true;
7847330f729Sjoerg }
7857330f729Sjoerg 
7867330f729Sjoerg /// Create a fixit to remove an if-like statement, on the assumption that its
7877330f729Sjoerg /// condition is CondVal.
CreateIfFixit(Sema & S,const Stmt * If,const Stmt * Then,const Stmt * Else,bool CondVal,FixItHint & Fixit1,FixItHint & Fixit2)7887330f729Sjoerg static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
7897330f729Sjoerg                           const Stmt *Else, bool CondVal,
7907330f729Sjoerg                           FixItHint &Fixit1, FixItHint &Fixit2) {
7917330f729Sjoerg   if (CondVal) {
7927330f729Sjoerg     // If condition is always true, remove all but the 'then'.
7937330f729Sjoerg     Fixit1 = FixItHint::CreateRemoval(
7947330f729Sjoerg         CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
7957330f729Sjoerg     if (Else) {
7967330f729Sjoerg       SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
7977330f729Sjoerg       Fixit2 =
7987330f729Sjoerg           FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
7997330f729Sjoerg     }
8007330f729Sjoerg   } else {
8017330f729Sjoerg     // If condition is always false, remove all but the 'else'.
8027330f729Sjoerg     if (Else)
8037330f729Sjoerg       Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
8047330f729Sjoerg           If->getBeginLoc(), Else->getBeginLoc()));
8057330f729Sjoerg     else
8067330f729Sjoerg       Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
8077330f729Sjoerg   }
8087330f729Sjoerg }
8097330f729Sjoerg 
8107330f729Sjoerg /// DiagUninitUse -- Helper function to produce a diagnostic for an
8117330f729Sjoerg /// uninitialized use of a variable.
DiagUninitUse(Sema & S,const VarDecl * VD,const UninitUse & Use,bool IsCapturedByBlock)8127330f729Sjoerg static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
8137330f729Sjoerg                           bool IsCapturedByBlock) {
8147330f729Sjoerg   bool Diagnosed = false;
8157330f729Sjoerg 
8167330f729Sjoerg   switch (Use.getKind()) {
8177330f729Sjoerg   case UninitUse::Always:
8187330f729Sjoerg     S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
8197330f729Sjoerg         << VD->getDeclName() << IsCapturedByBlock
8207330f729Sjoerg         << Use.getUser()->getSourceRange();
8217330f729Sjoerg     return;
8227330f729Sjoerg 
8237330f729Sjoerg   case UninitUse::AfterDecl:
8247330f729Sjoerg   case UninitUse::AfterCall:
8257330f729Sjoerg     S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
8267330f729Sjoerg       << VD->getDeclName() << IsCapturedByBlock
8277330f729Sjoerg       << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
8287330f729Sjoerg       << const_cast<DeclContext*>(VD->getLexicalDeclContext())
8297330f729Sjoerg       << VD->getSourceRange();
8307330f729Sjoerg     S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
8317330f729Sjoerg         << IsCapturedByBlock << Use.getUser()->getSourceRange();
8327330f729Sjoerg     return;
8337330f729Sjoerg 
8347330f729Sjoerg   case UninitUse::Maybe:
8357330f729Sjoerg   case UninitUse::Sometimes:
8367330f729Sjoerg     // Carry on to report sometimes-uninitialized branches, if possible,
8377330f729Sjoerg     // or a 'may be used uninitialized' diagnostic otherwise.
8387330f729Sjoerg     break;
8397330f729Sjoerg   }
8407330f729Sjoerg 
8417330f729Sjoerg   // Diagnose each branch which leads to a sometimes-uninitialized use.
8427330f729Sjoerg   for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
8437330f729Sjoerg        I != E; ++I) {
8447330f729Sjoerg     assert(Use.getKind() == UninitUse::Sometimes);
8457330f729Sjoerg 
8467330f729Sjoerg     const Expr *User = Use.getUser();
8477330f729Sjoerg     const Stmt *Term = I->Terminator;
8487330f729Sjoerg 
8497330f729Sjoerg     // Information used when building the diagnostic.
8507330f729Sjoerg     unsigned DiagKind;
8517330f729Sjoerg     StringRef Str;
8527330f729Sjoerg     SourceRange Range;
8537330f729Sjoerg 
8547330f729Sjoerg     // FixIts to suppress the diagnostic by removing the dead condition.
8557330f729Sjoerg     // For all binary terminators, branch 0 is taken if the condition is true,
8567330f729Sjoerg     // and branch 1 is taken if the condition is false.
8577330f729Sjoerg     int RemoveDiagKind = -1;
8587330f729Sjoerg     const char *FixitStr =
8597330f729Sjoerg         S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
8607330f729Sjoerg                                   : (I->Output ? "1" : "0");
8617330f729Sjoerg     FixItHint Fixit1, Fixit2;
8627330f729Sjoerg 
8637330f729Sjoerg     switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
8647330f729Sjoerg     default:
8657330f729Sjoerg       // Don't know how to report this. Just fall back to 'may be used
8667330f729Sjoerg       // uninitialized'. FIXME: Can this happen?
8677330f729Sjoerg       continue;
8687330f729Sjoerg 
8697330f729Sjoerg     // "condition is true / condition is false".
8707330f729Sjoerg     case Stmt::IfStmtClass: {
8717330f729Sjoerg       const IfStmt *IS = cast<IfStmt>(Term);
8727330f729Sjoerg       DiagKind = 0;
8737330f729Sjoerg       Str = "if";
8747330f729Sjoerg       Range = IS->getCond()->getSourceRange();
8757330f729Sjoerg       RemoveDiagKind = 0;
8767330f729Sjoerg       CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
8777330f729Sjoerg                     I->Output, Fixit1, Fixit2);
8787330f729Sjoerg       break;
8797330f729Sjoerg     }
8807330f729Sjoerg     case Stmt::ConditionalOperatorClass: {
8817330f729Sjoerg       const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
8827330f729Sjoerg       DiagKind = 0;
8837330f729Sjoerg       Str = "?:";
8847330f729Sjoerg       Range = CO->getCond()->getSourceRange();
8857330f729Sjoerg       RemoveDiagKind = 0;
8867330f729Sjoerg       CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
8877330f729Sjoerg                     I->Output, Fixit1, Fixit2);
8887330f729Sjoerg       break;
8897330f729Sjoerg     }
8907330f729Sjoerg     case Stmt::BinaryOperatorClass: {
8917330f729Sjoerg       const BinaryOperator *BO = cast<BinaryOperator>(Term);
8927330f729Sjoerg       if (!BO->isLogicalOp())
8937330f729Sjoerg         continue;
8947330f729Sjoerg       DiagKind = 0;
8957330f729Sjoerg       Str = BO->getOpcodeStr();
8967330f729Sjoerg       Range = BO->getLHS()->getSourceRange();
8977330f729Sjoerg       RemoveDiagKind = 0;
8987330f729Sjoerg       if ((BO->getOpcode() == BO_LAnd && I->Output) ||
8997330f729Sjoerg           (BO->getOpcode() == BO_LOr && !I->Output))
9007330f729Sjoerg         // true && y -> y, false || y -> y.
9017330f729Sjoerg         Fixit1 = FixItHint::CreateRemoval(
9027330f729Sjoerg             SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
9037330f729Sjoerg       else
9047330f729Sjoerg         // false && y -> false, true || y -> true.
9057330f729Sjoerg         Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
9067330f729Sjoerg       break;
9077330f729Sjoerg     }
9087330f729Sjoerg 
9097330f729Sjoerg     // "loop is entered / loop is exited".
9107330f729Sjoerg     case Stmt::WhileStmtClass:
9117330f729Sjoerg       DiagKind = 1;
9127330f729Sjoerg       Str = "while";
9137330f729Sjoerg       Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
9147330f729Sjoerg       RemoveDiagKind = 1;
9157330f729Sjoerg       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
9167330f729Sjoerg       break;
9177330f729Sjoerg     case Stmt::ForStmtClass:
9187330f729Sjoerg       DiagKind = 1;
9197330f729Sjoerg       Str = "for";
9207330f729Sjoerg       Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
9217330f729Sjoerg       RemoveDiagKind = 1;
9227330f729Sjoerg       if (I->Output)
9237330f729Sjoerg         Fixit1 = FixItHint::CreateRemoval(Range);
9247330f729Sjoerg       else
9257330f729Sjoerg         Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
9267330f729Sjoerg       break;
9277330f729Sjoerg     case Stmt::CXXForRangeStmtClass:
9287330f729Sjoerg       if (I->Output == 1) {
9297330f729Sjoerg         // The use occurs if a range-based for loop's body never executes.
9307330f729Sjoerg         // That may be impossible, and there's no syntactic fix for this,
9317330f729Sjoerg         // so treat it as a 'may be uninitialized' case.
9327330f729Sjoerg         continue;
9337330f729Sjoerg       }
9347330f729Sjoerg       DiagKind = 1;
9357330f729Sjoerg       Str = "for";
9367330f729Sjoerg       Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
9377330f729Sjoerg       break;
9387330f729Sjoerg 
9397330f729Sjoerg     // "condition is true / loop is exited".
9407330f729Sjoerg     case Stmt::DoStmtClass:
9417330f729Sjoerg       DiagKind = 2;
9427330f729Sjoerg       Str = "do";
9437330f729Sjoerg       Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
9447330f729Sjoerg       RemoveDiagKind = 1;
9457330f729Sjoerg       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
9467330f729Sjoerg       break;
9477330f729Sjoerg 
9487330f729Sjoerg     // "switch case is taken".
9497330f729Sjoerg     case Stmt::CaseStmtClass:
9507330f729Sjoerg       DiagKind = 3;
9517330f729Sjoerg       Str = "case";
9527330f729Sjoerg       Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
9537330f729Sjoerg       break;
9547330f729Sjoerg     case Stmt::DefaultStmtClass:
9557330f729Sjoerg       DiagKind = 3;
9567330f729Sjoerg       Str = "default";
9577330f729Sjoerg       Range = cast<DefaultStmt>(Term)->getDefaultLoc();
9587330f729Sjoerg       break;
9597330f729Sjoerg     }
9607330f729Sjoerg 
9617330f729Sjoerg     S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
9627330f729Sjoerg       << VD->getDeclName() << IsCapturedByBlock << DiagKind
9637330f729Sjoerg       << Str << I->Output << Range;
9647330f729Sjoerg     S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
9657330f729Sjoerg         << IsCapturedByBlock << User->getSourceRange();
9667330f729Sjoerg     if (RemoveDiagKind != -1)
9677330f729Sjoerg       S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
9687330f729Sjoerg         << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
9697330f729Sjoerg 
9707330f729Sjoerg     Diagnosed = true;
9717330f729Sjoerg   }
9727330f729Sjoerg 
9737330f729Sjoerg   if (!Diagnosed)
9747330f729Sjoerg     S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
9757330f729Sjoerg         << VD->getDeclName() << IsCapturedByBlock
9767330f729Sjoerg         << Use.getUser()->getSourceRange();
9777330f729Sjoerg }
9787330f729Sjoerg 
979*e038c9c4Sjoerg /// Diagnose uninitialized const reference usages.
DiagnoseUninitializedConstRefUse(Sema & S,const VarDecl * VD,const UninitUse & Use)980*e038c9c4Sjoerg static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD,
981*e038c9c4Sjoerg                                              const UninitUse &Use) {
982*e038c9c4Sjoerg   S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_const_reference)
983*e038c9c4Sjoerg       << VD->getDeclName() << Use.getUser()->getSourceRange();
984*e038c9c4Sjoerg   return true;
985*e038c9c4Sjoerg }
986*e038c9c4Sjoerg 
9877330f729Sjoerg /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
9887330f729Sjoerg /// uninitialized variable. This manages the different forms of diagnostic
9897330f729Sjoerg /// emitted for particular types of uses. Returns true if the use was diagnosed
9907330f729Sjoerg /// as a warning. If a particular use is one we omit warnings for, returns
9917330f729Sjoerg /// false.
DiagnoseUninitializedUse(Sema & S,const VarDecl * VD,const UninitUse & Use,bool alwaysReportSelfInit=false)9927330f729Sjoerg static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
9937330f729Sjoerg                                      const UninitUse &Use,
9947330f729Sjoerg                                      bool alwaysReportSelfInit = false) {
9957330f729Sjoerg   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
9967330f729Sjoerg     // Inspect the initializer of the variable declaration which is
9977330f729Sjoerg     // being referenced prior to its initialization. We emit
9987330f729Sjoerg     // specialized diagnostics for self-initialization, and we
9997330f729Sjoerg     // specifically avoid warning about self references which take the
10007330f729Sjoerg     // form of:
10017330f729Sjoerg     //
10027330f729Sjoerg     //   int x = x;
10037330f729Sjoerg     //
10047330f729Sjoerg     // This is used to indicate to GCC that 'x' is intentionally left
10057330f729Sjoerg     // uninitialized. Proven code paths which access 'x' in
10067330f729Sjoerg     // an uninitialized state after this will still warn.
10077330f729Sjoerg     if (const Expr *Initializer = VD->getInit()) {
10087330f729Sjoerg       if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
10097330f729Sjoerg         return false;
10107330f729Sjoerg 
10117330f729Sjoerg       ContainsReference CR(S.Context, DRE);
10127330f729Sjoerg       CR.Visit(Initializer);
10137330f729Sjoerg       if (CR.doesContainReference()) {
10147330f729Sjoerg         S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
10157330f729Sjoerg             << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
10167330f729Sjoerg         return true;
10177330f729Sjoerg       }
10187330f729Sjoerg     }
10197330f729Sjoerg 
10207330f729Sjoerg     DiagUninitUse(S, VD, Use, false);
10217330f729Sjoerg   } else {
10227330f729Sjoerg     const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
10237330f729Sjoerg     if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
10247330f729Sjoerg       S.Diag(BE->getBeginLoc(),
10257330f729Sjoerg              diag::warn_uninit_byref_blockvar_captured_by_block)
10267330f729Sjoerg           << VD->getDeclName()
10277330f729Sjoerg           << VD->getType().getQualifiers().hasObjCLifetime();
10287330f729Sjoerg     else
10297330f729Sjoerg       DiagUninitUse(S, VD, Use, true);
10307330f729Sjoerg   }
10317330f729Sjoerg 
10327330f729Sjoerg   // Report where the variable was declared when the use wasn't within
10337330f729Sjoerg   // the initializer of that declaration & we didn't already suggest
10347330f729Sjoerg   // an initialization fixit.
10357330f729Sjoerg   if (!SuggestInitializationFixit(S, VD))
10367330f729Sjoerg     S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
10377330f729Sjoerg         << VD->getDeclName();
10387330f729Sjoerg 
10397330f729Sjoerg   return true;
10407330f729Sjoerg }
10417330f729Sjoerg 
10427330f729Sjoerg namespace {
10437330f729Sjoerg   class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
10447330f729Sjoerg   public:
FallthroughMapper(Sema & S)10457330f729Sjoerg     FallthroughMapper(Sema &S)
10467330f729Sjoerg       : FoundSwitchStatements(false),
10477330f729Sjoerg         S(S) {
10487330f729Sjoerg     }
10497330f729Sjoerg 
foundSwitchStatements() const10507330f729Sjoerg     bool foundSwitchStatements() const { return FoundSwitchStatements; }
10517330f729Sjoerg 
markFallthroughVisited(const AttributedStmt * Stmt)10527330f729Sjoerg     void markFallthroughVisited(const AttributedStmt *Stmt) {
10537330f729Sjoerg       bool Found = FallthroughStmts.erase(Stmt);
10547330f729Sjoerg       assert(Found);
10557330f729Sjoerg       (void)Found;
10567330f729Sjoerg     }
10577330f729Sjoerg 
10587330f729Sjoerg     typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
10597330f729Sjoerg 
getFallthroughStmts() const10607330f729Sjoerg     const AttrStmts &getFallthroughStmts() const {
10617330f729Sjoerg       return FallthroughStmts;
10627330f729Sjoerg     }
10637330f729Sjoerg 
fillReachableBlocks(CFG * Cfg)10647330f729Sjoerg     void fillReachableBlocks(CFG *Cfg) {
10657330f729Sjoerg       assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
10667330f729Sjoerg       std::deque<const CFGBlock *> BlockQueue;
10677330f729Sjoerg 
10687330f729Sjoerg       ReachableBlocks.insert(&Cfg->getEntry());
10697330f729Sjoerg       BlockQueue.push_back(&Cfg->getEntry());
10707330f729Sjoerg       // Mark all case blocks reachable to avoid problems with switching on
10717330f729Sjoerg       // constants, covered enums, etc.
10727330f729Sjoerg       // These blocks can contain fall-through annotations, and we don't want to
10737330f729Sjoerg       // issue a warn_fallthrough_attr_unreachable for them.
10747330f729Sjoerg       for (const auto *B : *Cfg) {
10757330f729Sjoerg         const Stmt *L = B->getLabel();
10767330f729Sjoerg         if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
10777330f729Sjoerg           BlockQueue.push_back(B);
10787330f729Sjoerg       }
10797330f729Sjoerg 
10807330f729Sjoerg       while (!BlockQueue.empty()) {
10817330f729Sjoerg         const CFGBlock *P = BlockQueue.front();
10827330f729Sjoerg         BlockQueue.pop_front();
10837330f729Sjoerg         for (CFGBlock::const_succ_iterator I = P->succ_begin(),
10847330f729Sjoerg                                            E = P->succ_end();
10857330f729Sjoerg              I != E; ++I) {
10867330f729Sjoerg           if (*I && ReachableBlocks.insert(*I).second)
10877330f729Sjoerg             BlockQueue.push_back(*I);
10887330f729Sjoerg         }
10897330f729Sjoerg       }
10907330f729Sjoerg     }
10917330f729Sjoerg 
checkFallThroughIntoBlock(const CFGBlock & B,int & AnnotatedCnt,bool IsTemplateInstantiation)10927330f729Sjoerg     bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
10937330f729Sjoerg                                    bool IsTemplateInstantiation) {
10947330f729Sjoerg       assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
10957330f729Sjoerg 
10967330f729Sjoerg       int UnannotatedCnt = 0;
10977330f729Sjoerg       AnnotatedCnt = 0;
10987330f729Sjoerg 
10997330f729Sjoerg       std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
11007330f729Sjoerg       while (!BlockQueue.empty()) {
11017330f729Sjoerg         const CFGBlock *P = BlockQueue.front();
11027330f729Sjoerg         BlockQueue.pop_front();
11037330f729Sjoerg         if (!P) continue;
11047330f729Sjoerg 
11057330f729Sjoerg         const Stmt *Term = P->getTerminatorStmt();
11067330f729Sjoerg         if (Term && isa<SwitchStmt>(Term))
11077330f729Sjoerg           continue; // Switch statement, good.
11087330f729Sjoerg 
11097330f729Sjoerg         const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
11107330f729Sjoerg         if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
11117330f729Sjoerg           continue; // Previous case label has no statements, good.
11127330f729Sjoerg 
11137330f729Sjoerg         const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
11147330f729Sjoerg         if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
11157330f729Sjoerg           continue; // Case label is preceded with a normal label, good.
11167330f729Sjoerg 
11177330f729Sjoerg         if (!ReachableBlocks.count(P)) {
11187330f729Sjoerg           for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
11197330f729Sjoerg                                                 ElemEnd = P->rend();
11207330f729Sjoerg                ElemIt != ElemEnd; ++ElemIt) {
11217330f729Sjoerg             if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
11227330f729Sjoerg               if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
11237330f729Sjoerg                 // Don't issue a warning for an unreachable fallthrough
11247330f729Sjoerg                 // attribute in template instantiations as it may not be
11257330f729Sjoerg                 // unreachable in all instantiations of the template.
11267330f729Sjoerg                 if (!IsTemplateInstantiation)
11277330f729Sjoerg                   S.Diag(AS->getBeginLoc(),
11287330f729Sjoerg                          diag::warn_fallthrough_attr_unreachable);
11297330f729Sjoerg                 markFallthroughVisited(AS);
11307330f729Sjoerg                 ++AnnotatedCnt;
11317330f729Sjoerg                 break;
11327330f729Sjoerg               }
11337330f729Sjoerg               // Don't care about other unreachable statements.
11347330f729Sjoerg             }
11357330f729Sjoerg           }
11367330f729Sjoerg           // If there are no unreachable statements, this may be a special
11377330f729Sjoerg           // case in CFG:
11387330f729Sjoerg           // case X: {
11397330f729Sjoerg           //    A a;  // A has a destructor.
11407330f729Sjoerg           //    break;
11417330f729Sjoerg           // }
11427330f729Sjoerg           // // <<<< This place is represented by a 'hanging' CFG block.
11437330f729Sjoerg           // case Y:
11447330f729Sjoerg           continue;
11457330f729Sjoerg         }
11467330f729Sjoerg 
11477330f729Sjoerg         const Stmt *LastStmt = getLastStmt(*P);
11487330f729Sjoerg         if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
11497330f729Sjoerg           markFallthroughVisited(AS);
11507330f729Sjoerg           ++AnnotatedCnt;
11517330f729Sjoerg           continue; // Fallthrough annotation, good.
11527330f729Sjoerg         }
11537330f729Sjoerg 
11547330f729Sjoerg         if (!LastStmt) { // This block contains no executable statements.
11557330f729Sjoerg           // Traverse its predecessors.
11567330f729Sjoerg           std::copy(P->pred_begin(), P->pred_end(),
11577330f729Sjoerg                     std::back_inserter(BlockQueue));
11587330f729Sjoerg           continue;
11597330f729Sjoerg         }
11607330f729Sjoerg 
11617330f729Sjoerg         ++UnannotatedCnt;
11627330f729Sjoerg       }
11637330f729Sjoerg       return !!UnannotatedCnt;
11647330f729Sjoerg     }
11657330f729Sjoerg 
11667330f729Sjoerg     // RecursiveASTVisitor setup.
shouldWalkTypesOfTypeLocs() const11677330f729Sjoerg     bool shouldWalkTypesOfTypeLocs() const { return false; }
11687330f729Sjoerg 
VisitAttributedStmt(AttributedStmt * S)11697330f729Sjoerg     bool VisitAttributedStmt(AttributedStmt *S) {
11707330f729Sjoerg       if (asFallThroughAttr(S))
11717330f729Sjoerg         FallthroughStmts.insert(S);
11727330f729Sjoerg       return true;
11737330f729Sjoerg     }
11747330f729Sjoerg 
VisitSwitchStmt(SwitchStmt * S)11757330f729Sjoerg     bool VisitSwitchStmt(SwitchStmt *S) {
11767330f729Sjoerg       FoundSwitchStatements = true;
11777330f729Sjoerg       return true;
11787330f729Sjoerg     }
11797330f729Sjoerg 
11807330f729Sjoerg     // We don't want to traverse local type declarations. We analyze their
11817330f729Sjoerg     // methods separately.
TraverseDecl(Decl * D)11827330f729Sjoerg     bool TraverseDecl(Decl *D) { return true; }
11837330f729Sjoerg 
11847330f729Sjoerg     // We analyze lambda bodies separately. Skip them here.
TraverseLambdaExpr(LambdaExpr * LE)11857330f729Sjoerg     bool TraverseLambdaExpr(LambdaExpr *LE) {
11867330f729Sjoerg       // Traverse the captures, but not the body.
1187*e038c9c4Sjoerg       for (const auto C : zip(LE->captures(), LE->capture_inits()))
11887330f729Sjoerg         TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
11897330f729Sjoerg       return true;
11907330f729Sjoerg     }
11917330f729Sjoerg 
11927330f729Sjoerg   private:
11937330f729Sjoerg 
asFallThroughAttr(const Stmt * S)11947330f729Sjoerg     static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
11957330f729Sjoerg       if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
11967330f729Sjoerg         if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
11977330f729Sjoerg           return AS;
11987330f729Sjoerg       }
11997330f729Sjoerg       return nullptr;
12007330f729Sjoerg     }
12017330f729Sjoerg 
getLastStmt(const CFGBlock & B)12027330f729Sjoerg     static const Stmt *getLastStmt(const CFGBlock &B) {
12037330f729Sjoerg       if (const Stmt *Term = B.getTerminatorStmt())
12047330f729Sjoerg         return Term;
12057330f729Sjoerg       for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
12067330f729Sjoerg                                             ElemEnd = B.rend();
12077330f729Sjoerg                                             ElemIt != ElemEnd; ++ElemIt) {
12087330f729Sjoerg         if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
12097330f729Sjoerg           return CS->getStmt();
12107330f729Sjoerg       }
12117330f729Sjoerg       // Workaround to detect a statement thrown out by CFGBuilder:
12127330f729Sjoerg       //   case X: {} case Y:
12137330f729Sjoerg       //   case X: ; case Y:
12147330f729Sjoerg       if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
12157330f729Sjoerg         if (!isa<SwitchCase>(SW->getSubStmt()))
12167330f729Sjoerg           return SW->getSubStmt();
12177330f729Sjoerg 
12187330f729Sjoerg       return nullptr;
12197330f729Sjoerg     }
12207330f729Sjoerg 
12217330f729Sjoerg     bool FoundSwitchStatements;
12227330f729Sjoerg     AttrStmts FallthroughStmts;
12237330f729Sjoerg     Sema &S;
12247330f729Sjoerg     llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
12257330f729Sjoerg   };
12267330f729Sjoerg } // anonymous namespace
12277330f729Sjoerg 
getFallthroughAttrSpelling(Preprocessor & PP,SourceLocation Loc)12287330f729Sjoerg static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
12297330f729Sjoerg                                             SourceLocation Loc) {
12307330f729Sjoerg   TokenValue FallthroughTokens[] = {
12317330f729Sjoerg     tok::l_square, tok::l_square,
12327330f729Sjoerg     PP.getIdentifierInfo("fallthrough"),
12337330f729Sjoerg     tok::r_square, tok::r_square
12347330f729Sjoerg   };
12357330f729Sjoerg 
12367330f729Sjoerg   TokenValue ClangFallthroughTokens[] = {
12377330f729Sjoerg     tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
12387330f729Sjoerg     tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
12397330f729Sjoerg     tok::r_square, tok::r_square
12407330f729Sjoerg   };
12417330f729Sjoerg 
12427330f729Sjoerg   bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C2x;
12437330f729Sjoerg 
12447330f729Sjoerg   StringRef MacroName;
12457330f729Sjoerg   if (PreferClangAttr)
12467330f729Sjoerg     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
12477330f729Sjoerg   if (MacroName.empty())
12487330f729Sjoerg     MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
12497330f729Sjoerg   if (MacroName.empty() && !PreferClangAttr)
12507330f729Sjoerg     MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
12517330f729Sjoerg   if (MacroName.empty()) {
12527330f729Sjoerg     if (!PreferClangAttr)
12537330f729Sjoerg       MacroName = "[[fallthrough]]";
12547330f729Sjoerg     else if (PP.getLangOpts().CPlusPlus)
12557330f729Sjoerg       MacroName = "[[clang::fallthrough]]";
12567330f729Sjoerg     else
12577330f729Sjoerg       MacroName = "__attribute__((fallthrough))";
12587330f729Sjoerg   }
12597330f729Sjoerg   return MacroName;
12607330f729Sjoerg }
12617330f729Sjoerg 
DiagnoseSwitchLabelsFallthrough(Sema & S,AnalysisDeclContext & AC,bool PerFunction)12627330f729Sjoerg static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
12637330f729Sjoerg                                             bool PerFunction) {
12647330f729Sjoerg   FallthroughMapper FM(S);
12657330f729Sjoerg   FM.TraverseStmt(AC.getBody());
12667330f729Sjoerg 
12677330f729Sjoerg   if (!FM.foundSwitchStatements())
12687330f729Sjoerg     return;
12697330f729Sjoerg 
12707330f729Sjoerg   if (PerFunction && FM.getFallthroughStmts().empty())
12717330f729Sjoerg     return;
12727330f729Sjoerg 
12737330f729Sjoerg   CFG *Cfg = AC.getCFG();
12747330f729Sjoerg 
12757330f729Sjoerg   if (!Cfg)
12767330f729Sjoerg     return;
12777330f729Sjoerg 
12787330f729Sjoerg   FM.fillReachableBlocks(Cfg);
12797330f729Sjoerg 
12807330f729Sjoerg   for (const CFGBlock *B : llvm::reverse(*Cfg)) {
12817330f729Sjoerg     const Stmt *Label = B->getLabel();
12827330f729Sjoerg 
12837330f729Sjoerg     if (!Label || !isa<SwitchCase>(Label))
12847330f729Sjoerg       continue;
12857330f729Sjoerg 
12867330f729Sjoerg     int AnnotatedCnt;
12877330f729Sjoerg 
12887330f729Sjoerg     bool IsTemplateInstantiation = false;
12897330f729Sjoerg     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
12907330f729Sjoerg       IsTemplateInstantiation = Function->isTemplateInstantiation();
12917330f729Sjoerg     if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
12927330f729Sjoerg                                       IsTemplateInstantiation))
12937330f729Sjoerg       continue;
12947330f729Sjoerg 
12957330f729Sjoerg     S.Diag(Label->getBeginLoc(),
12967330f729Sjoerg            PerFunction ? diag::warn_unannotated_fallthrough_per_function
12977330f729Sjoerg                        : diag::warn_unannotated_fallthrough);
12987330f729Sjoerg 
12997330f729Sjoerg     if (!AnnotatedCnt) {
13007330f729Sjoerg       SourceLocation L = Label->getBeginLoc();
13017330f729Sjoerg       if (L.isMacroID())
13027330f729Sjoerg         continue;
13037330f729Sjoerg 
13047330f729Sjoerg       const Stmt *Term = B->getTerminatorStmt();
13057330f729Sjoerg       // Skip empty cases.
13067330f729Sjoerg       while (B->empty() && !Term && B->succ_size() == 1) {
13077330f729Sjoerg         B = *B->succ_begin();
13087330f729Sjoerg         Term = B->getTerminatorStmt();
13097330f729Sjoerg       }
13107330f729Sjoerg       if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
13117330f729Sjoerg         Preprocessor &PP = S.getPreprocessor();
13127330f729Sjoerg         StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
13137330f729Sjoerg         SmallString<64> TextToInsert(AnnotationSpelling);
13147330f729Sjoerg         TextToInsert += "; ";
13157330f729Sjoerg         S.Diag(L, diag::note_insert_fallthrough_fixit)
13167330f729Sjoerg             << AnnotationSpelling
13177330f729Sjoerg             << FixItHint::CreateInsertion(L, TextToInsert);
13187330f729Sjoerg       }
13197330f729Sjoerg       S.Diag(L, diag::note_insert_break_fixit)
13207330f729Sjoerg           << FixItHint::CreateInsertion(L, "break; ");
13217330f729Sjoerg     }
13227330f729Sjoerg   }
13237330f729Sjoerg 
13247330f729Sjoerg   for (const auto *F : FM.getFallthroughStmts())
13257330f729Sjoerg     S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
13267330f729Sjoerg }
13277330f729Sjoerg 
isInLoop(const ASTContext & Ctx,const ParentMap & PM,const Stmt * S)13287330f729Sjoerg static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
13297330f729Sjoerg                      const Stmt *S) {
13307330f729Sjoerg   assert(S);
13317330f729Sjoerg 
13327330f729Sjoerg   do {
13337330f729Sjoerg     switch (S->getStmtClass()) {
13347330f729Sjoerg     case Stmt::ForStmtClass:
13357330f729Sjoerg     case Stmt::WhileStmtClass:
13367330f729Sjoerg     case Stmt::CXXForRangeStmtClass:
13377330f729Sjoerg     case Stmt::ObjCForCollectionStmtClass:
13387330f729Sjoerg       return true;
13397330f729Sjoerg     case Stmt::DoStmtClass: {
13407330f729Sjoerg       Expr::EvalResult Result;
13417330f729Sjoerg       if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
13427330f729Sjoerg         return true;
13437330f729Sjoerg       return Result.Val.getInt().getBoolValue();
13447330f729Sjoerg     }
13457330f729Sjoerg     default:
13467330f729Sjoerg       break;
13477330f729Sjoerg     }
13487330f729Sjoerg   } while ((S = PM.getParent(S)));
13497330f729Sjoerg 
13507330f729Sjoerg   return false;
13517330f729Sjoerg }
13527330f729Sjoerg 
diagnoseRepeatedUseOfWeak(Sema & S,const sema::FunctionScopeInfo * CurFn,const Decl * D,const ParentMap & PM)13537330f729Sjoerg static void diagnoseRepeatedUseOfWeak(Sema &S,
13547330f729Sjoerg                                       const sema::FunctionScopeInfo *CurFn,
13557330f729Sjoerg                                       const Decl *D,
13567330f729Sjoerg                                       const ParentMap &PM) {
13577330f729Sjoerg   typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
13587330f729Sjoerg   typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
13597330f729Sjoerg   typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
13607330f729Sjoerg   typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
13617330f729Sjoerg   StmtUsesPair;
13627330f729Sjoerg 
13637330f729Sjoerg   ASTContext &Ctx = S.getASTContext();
13647330f729Sjoerg 
13657330f729Sjoerg   const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
13667330f729Sjoerg 
13677330f729Sjoerg   // Extract all weak objects that are referenced more than once.
13687330f729Sjoerg   SmallVector<StmtUsesPair, 8> UsesByStmt;
13697330f729Sjoerg   for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
13707330f729Sjoerg        I != E; ++I) {
13717330f729Sjoerg     const WeakUseVector &Uses = I->second;
13727330f729Sjoerg 
13737330f729Sjoerg     // Find the first read of the weak object.
13747330f729Sjoerg     WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
13757330f729Sjoerg     for ( ; UI != UE; ++UI) {
13767330f729Sjoerg       if (UI->isUnsafe())
13777330f729Sjoerg         break;
13787330f729Sjoerg     }
13797330f729Sjoerg 
13807330f729Sjoerg     // If there were only writes to this object, don't warn.
13817330f729Sjoerg     if (UI == UE)
13827330f729Sjoerg       continue;
13837330f729Sjoerg 
13847330f729Sjoerg     // If there was only one read, followed by any number of writes, and the
13857330f729Sjoerg     // read is not within a loop, don't warn. Additionally, don't warn in a
13867330f729Sjoerg     // loop if the base object is a local variable -- local variables are often
13877330f729Sjoerg     // changed in loops.
13887330f729Sjoerg     if (UI == Uses.begin()) {
13897330f729Sjoerg       WeakUseVector::const_iterator UI2 = UI;
13907330f729Sjoerg       for (++UI2; UI2 != UE; ++UI2)
13917330f729Sjoerg         if (UI2->isUnsafe())
13927330f729Sjoerg           break;
13937330f729Sjoerg 
13947330f729Sjoerg       if (UI2 == UE) {
13957330f729Sjoerg         if (!isInLoop(Ctx, PM, UI->getUseExpr()))
13967330f729Sjoerg           continue;
13977330f729Sjoerg 
13987330f729Sjoerg         const WeakObjectProfileTy &Profile = I->first;
13997330f729Sjoerg         if (!Profile.isExactProfile())
14007330f729Sjoerg           continue;
14017330f729Sjoerg 
14027330f729Sjoerg         const NamedDecl *Base = Profile.getBase();
14037330f729Sjoerg         if (!Base)
14047330f729Sjoerg           Base = Profile.getProperty();
14057330f729Sjoerg         assert(Base && "A profile always has a base or property.");
14067330f729Sjoerg 
14077330f729Sjoerg         if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
14087330f729Sjoerg           if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
14097330f729Sjoerg             continue;
14107330f729Sjoerg       }
14117330f729Sjoerg     }
14127330f729Sjoerg 
14137330f729Sjoerg     UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
14147330f729Sjoerg   }
14157330f729Sjoerg 
14167330f729Sjoerg   if (UsesByStmt.empty())
14177330f729Sjoerg     return;
14187330f729Sjoerg 
14197330f729Sjoerg   // Sort by first use so that we emit the warnings in a deterministic order.
14207330f729Sjoerg   SourceManager &SM = S.getSourceManager();
14217330f729Sjoerg   llvm::sort(UsesByStmt,
14227330f729Sjoerg              [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
14237330f729Sjoerg                return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
14247330f729Sjoerg                                                    RHS.first->getBeginLoc());
14257330f729Sjoerg              });
14267330f729Sjoerg 
14277330f729Sjoerg   // Classify the current code body for better warning text.
14287330f729Sjoerg   // This enum should stay in sync with the cases in
14297330f729Sjoerg   // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
14307330f729Sjoerg   // FIXME: Should we use a common classification enum and the same set of
14317330f729Sjoerg   // possibilities all throughout Sema?
14327330f729Sjoerg   enum {
14337330f729Sjoerg     Function,
14347330f729Sjoerg     Method,
14357330f729Sjoerg     Block,
14367330f729Sjoerg     Lambda
14377330f729Sjoerg   } FunctionKind;
14387330f729Sjoerg 
14397330f729Sjoerg   if (isa<sema::BlockScopeInfo>(CurFn))
14407330f729Sjoerg     FunctionKind = Block;
14417330f729Sjoerg   else if (isa<sema::LambdaScopeInfo>(CurFn))
14427330f729Sjoerg     FunctionKind = Lambda;
14437330f729Sjoerg   else if (isa<ObjCMethodDecl>(D))
14447330f729Sjoerg     FunctionKind = Method;
14457330f729Sjoerg   else
14467330f729Sjoerg     FunctionKind = Function;
14477330f729Sjoerg 
14487330f729Sjoerg   // Iterate through the sorted problems and emit warnings for each.
14497330f729Sjoerg   for (const auto &P : UsesByStmt) {
14507330f729Sjoerg     const Stmt *FirstRead = P.first;
14517330f729Sjoerg     const WeakObjectProfileTy &Key = P.second->first;
14527330f729Sjoerg     const WeakUseVector &Uses = P.second->second;
14537330f729Sjoerg 
14547330f729Sjoerg     // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
14557330f729Sjoerg     // may not contain enough information to determine that these are different
14567330f729Sjoerg     // properties. We can only be 100% sure of a repeated use in certain cases,
14577330f729Sjoerg     // and we adjust the diagnostic kind accordingly so that the less certain
14587330f729Sjoerg     // case can be turned off if it is too noisy.
14597330f729Sjoerg     unsigned DiagKind;
14607330f729Sjoerg     if (Key.isExactProfile())
14617330f729Sjoerg       DiagKind = diag::warn_arc_repeated_use_of_weak;
14627330f729Sjoerg     else
14637330f729Sjoerg       DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
14647330f729Sjoerg 
14657330f729Sjoerg     // Classify the weak object being accessed for better warning text.
14667330f729Sjoerg     // This enum should stay in sync with the cases in
14677330f729Sjoerg     // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
14687330f729Sjoerg     enum {
14697330f729Sjoerg       Variable,
14707330f729Sjoerg       Property,
14717330f729Sjoerg       ImplicitProperty,
14727330f729Sjoerg       Ivar
14737330f729Sjoerg     } ObjectKind;
14747330f729Sjoerg 
14757330f729Sjoerg     const NamedDecl *KeyProp = Key.getProperty();
14767330f729Sjoerg     if (isa<VarDecl>(KeyProp))
14777330f729Sjoerg       ObjectKind = Variable;
14787330f729Sjoerg     else if (isa<ObjCPropertyDecl>(KeyProp))
14797330f729Sjoerg       ObjectKind = Property;
14807330f729Sjoerg     else if (isa<ObjCMethodDecl>(KeyProp))
14817330f729Sjoerg       ObjectKind = ImplicitProperty;
14827330f729Sjoerg     else if (isa<ObjCIvarDecl>(KeyProp))
14837330f729Sjoerg       ObjectKind = Ivar;
14847330f729Sjoerg     else
14857330f729Sjoerg       llvm_unreachable("Unexpected weak object kind!");
14867330f729Sjoerg 
14877330f729Sjoerg     // Do not warn about IBOutlet weak property receivers being set to null
14887330f729Sjoerg     // since they are typically only used from the main thread.
14897330f729Sjoerg     if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
14907330f729Sjoerg       if (Prop->hasAttr<IBOutletAttr>())
14917330f729Sjoerg         continue;
14927330f729Sjoerg 
14937330f729Sjoerg     // Show the first time the object was read.
14947330f729Sjoerg     S.Diag(FirstRead->getBeginLoc(), DiagKind)
14957330f729Sjoerg         << int(ObjectKind) << KeyProp << int(FunctionKind)
14967330f729Sjoerg         << FirstRead->getSourceRange();
14977330f729Sjoerg 
14987330f729Sjoerg     // Print all the other accesses as notes.
14997330f729Sjoerg     for (const auto &Use : Uses) {
15007330f729Sjoerg       if (Use.getUseExpr() == FirstRead)
15017330f729Sjoerg         continue;
15027330f729Sjoerg       S.Diag(Use.getUseExpr()->getBeginLoc(),
15037330f729Sjoerg              diag::note_arc_weak_also_accessed_here)
15047330f729Sjoerg           << Use.getUseExpr()->getSourceRange();
15057330f729Sjoerg     }
15067330f729Sjoerg   }
15077330f729Sjoerg }
15087330f729Sjoerg 
1509*e038c9c4Sjoerg namespace clang {
1510*e038c9c4Sjoerg namespace {
1511*e038c9c4Sjoerg typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1512*e038c9c4Sjoerg typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1513*e038c9c4Sjoerg typedef std::list<DelayedDiag> DiagList;
1514*e038c9c4Sjoerg 
1515*e038c9c4Sjoerg struct SortDiagBySourceLocation {
1516*e038c9c4Sjoerg   SourceManager &SM;
SortDiagBySourceLocationclang::__anondf82a8a60c11::SortDiagBySourceLocation1517*e038c9c4Sjoerg   SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1518*e038c9c4Sjoerg 
operator ()clang::__anondf82a8a60c11::SortDiagBySourceLocation1519*e038c9c4Sjoerg   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1520*e038c9c4Sjoerg     // Although this call will be slow, this is only called when outputting
1521*e038c9c4Sjoerg     // multiple warnings.
1522*e038c9c4Sjoerg     return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1523*e038c9c4Sjoerg   }
1524*e038c9c4Sjoerg };
1525*e038c9c4Sjoerg } // anonymous namespace
1526*e038c9c4Sjoerg } // namespace clang
1527*e038c9c4Sjoerg 
15287330f729Sjoerg namespace {
15297330f729Sjoerg class UninitValsDiagReporter : public UninitVariablesHandler {
15307330f729Sjoerg   Sema &S;
15317330f729Sjoerg   typedef SmallVector<UninitUse, 2> UsesVec;
15327330f729Sjoerg   typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
15337330f729Sjoerg   // Prefer using MapVector to DenseMap, so that iteration order will be
15347330f729Sjoerg   // the same as insertion order. This is needed to obtain a deterministic
15357330f729Sjoerg   // order of diagnostics when calling flushDiagnostics().
15367330f729Sjoerg   typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
15377330f729Sjoerg   UsesMap uses;
1538*e038c9c4Sjoerg   UsesMap constRefUses;
15397330f729Sjoerg 
15407330f729Sjoerg public:
UninitValsDiagReporter(Sema & S)15417330f729Sjoerg   UninitValsDiagReporter(Sema &S) : S(S) {}
~UninitValsDiagReporter()15427330f729Sjoerg   ~UninitValsDiagReporter() override { flushDiagnostics(); }
15437330f729Sjoerg 
getUses(UsesMap & um,const VarDecl * vd)1544*e038c9c4Sjoerg   MappedType &getUses(UsesMap &um, const VarDecl *vd) {
1545*e038c9c4Sjoerg     MappedType &V = um[vd];
15467330f729Sjoerg     if (!V.getPointer())
15477330f729Sjoerg       V.setPointer(new UsesVec());
15487330f729Sjoerg     return V;
15497330f729Sjoerg   }
15507330f729Sjoerg 
handleUseOfUninitVariable(const VarDecl * vd,const UninitUse & use)15517330f729Sjoerg   void handleUseOfUninitVariable(const VarDecl *vd,
15527330f729Sjoerg                                  const UninitUse &use) override {
1553*e038c9c4Sjoerg     getUses(uses, vd).getPointer()->push_back(use);
1554*e038c9c4Sjoerg   }
1555*e038c9c4Sjoerg 
handleConstRefUseOfUninitVariable(const VarDecl * vd,const UninitUse & use)1556*e038c9c4Sjoerg   void handleConstRefUseOfUninitVariable(const VarDecl *vd,
1557*e038c9c4Sjoerg                                          const UninitUse &use) override {
1558*e038c9c4Sjoerg     getUses(constRefUses, vd).getPointer()->push_back(use);
15597330f729Sjoerg   }
15607330f729Sjoerg 
handleSelfInit(const VarDecl * vd)15617330f729Sjoerg   void handleSelfInit(const VarDecl *vd) override {
1562*e038c9c4Sjoerg     getUses(uses, vd).setInt(true);
1563*e038c9c4Sjoerg     getUses(constRefUses, vd).setInt(true);
15647330f729Sjoerg   }
15657330f729Sjoerg 
flushDiagnostics()15667330f729Sjoerg   void flushDiagnostics() {
15677330f729Sjoerg     for (const auto &P : uses) {
15687330f729Sjoerg       const VarDecl *vd = P.first;
15697330f729Sjoerg       const MappedType &V = P.second;
15707330f729Sjoerg 
15717330f729Sjoerg       UsesVec *vec = V.getPointer();
15727330f729Sjoerg       bool hasSelfInit = V.getInt();
15737330f729Sjoerg 
15747330f729Sjoerg       // Specially handle the case where we have uses of an uninitialized
15757330f729Sjoerg       // variable, but the root cause is an idiomatic self-init.  We want
15767330f729Sjoerg       // to report the diagnostic at the self-init since that is the root cause.
15777330f729Sjoerg       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
15787330f729Sjoerg         DiagnoseUninitializedUse(S, vd,
15797330f729Sjoerg                                  UninitUse(vd->getInit()->IgnoreParenCasts(),
15807330f729Sjoerg                                            /* isAlwaysUninit */ true),
15817330f729Sjoerg                                  /* alwaysReportSelfInit */ true);
15827330f729Sjoerg       else {
15837330f729Sjoerg         // Sort the uses by their SourceLocations.  While not strictly
15847330f729Sjoerg         // guaranteed to produce them in line/column order, this will provide
15857330f729Sjoerg         // a stable ordering.
15867330f729Sjoerg         llvm::sort(vec->begin(), vec->end(),
15877330f729Sjoerg                    [](const UninitUse &a, const UninitUse &b) {
15887330f729Sjoerg           // Prefer a more confident report over a less confident one.
15897330f729Sjoerg           if (a.getKind() != b.getKind())
15907330f729Sjoerg             return a.getKind() > b.getKind();
15917330f729Sjoerg           return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
15927330f729Sjoerg         });
15937330f729Sjoerg 
15947330f729Sjoerg         for (const auto &U : *vec) {
15957330f729Sjoerg           // If we have self-init, downgrade all uses to 'may be uninitialized'.
15967330f729Sjoerg           UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
15977330f729Sjoerg 
15987330f729Sjoerg           if (DiagnoseUninitializedUse(S, vd, Use))
15997330f729Sjoerg             // Skip further diagnostics for this variable. We try to warn only
16007330f729Sjoerg             // on the first point at which a variable is used uninitialized.
16017330f729Sjoerg             break;
16027330f729Sjoerg         }
16037330f729Sjoerg       }
16047330f729Sjoerg 
16057330f729Sjoerg       // Release the uses vector.
16067330f729Sjoerg       delete vec;
16077330f729Sjoerg     }
16087330f729Sjoerg 
16097330f729Sjoerg     uses.clear();
1610*e038c9c4Sjoerg 
1611*e038c9c4Sjoerg     // Flush all const reference uses diags.
1612*e038c9c4Sjoerg     for (const auto &P : constRefUses) {
1613*e038c9c4Sjoerg       const VarDecl *vd = P.first;
1614*e038c9c4Sjoerg       const MappedType &V = P.second;
1615*e038c9c4Sjoerg 
1616*e038c9c4Sjoerg       UsesVec *vec = V.getPointer();
1617*e038c9c4Sjoerg       bool hasSelfInit = V.getInt();
1618*e038c9c4Sjoerg 
1619*e038c9c4Sjoerg       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1620*e038c9c4Sjoerg         DiagnoseUninitializedUse(S, vd,
1621*e038c9c4Sjoerg                                  UninitUse(vd->getInit()->IgnoreParenCasts(),
1622*e038c9c4Sjoerg                                            /* isAlwaysUninit */ true),
1623*e038c9c4Sjoerg                                  /* alwaysReportSelfInit */ true);
1624*e038c9c4Sjoerg       else {
1625*e038c9c4Sjoerg         for (const auto &U : *vec) {
1626*e038c9c4Sjoerg           if (DiagnoseUninitializedConstRefUse(S, vd, U))
1627*e038c9c4Sjoerg             break;
1628*e038c9c4Sjoerg         }
1629*e038c9c4Sjoerg       }
1630*e038c9c4Sjoerg 
1631*e038c9c4Sjoerg       // Release the uses vector.
1632*e038c9c4Sjoerg       delete vec;
1633*e038c9c4Sjoerg     }
1634*e038c9c4Sjoerg 
1635*e038c9c4Sjoerg     constRefUses.clear();
16367330f729Sjoerg   }
16377330f729Sjoerg 
16387330f729Sjoerg private:
hasAlwaysUninitializedUse(const UsesVec * vec)16397330f729Sjoerg   static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
16407330f729Sjoerg     return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
16417330f729Sjoerg       return U.getKind() == UninitUse::Always ||
16427330f729Sjoerg              U.getKind() == UninitUse::AfterCall ||
16437330f729Sjoerg              U.getKind() == UninitUse::AfterDecl;
16447330f729Sjoerg     });
16457330f729Sjoerg   }
16467330f729Sjoerg };
16477330f729Sjoerg 
1648*e038c9c4Sjoerg /// Inter-procedural data for the called-once checker.
1649*e038c9c4Sjoerg class CalledOnceInterProceduralData {
1650*e038c9c4Sjoerg public:
1651*e038c9c4Sjoerg   // Add the delayed warning for the given block.
addDelayedWarning(const BlockDecl * Block,PartialDiagnosticAt && Warning)1652*e038c9c4Sjoerg   void addDelayedWarning(const BlockDecl *Block,
1653*e038c9c4Sjoerg                          PartialDiagnosticAt &&Warning) {
1654*e038c9c4Sjoerg     DelayedBlockWarnings[Block].emplace_back(std::move(Warning));
16557330f729Sjoerg   }
1656*e038c9c4Sjoerg   // Report all of the warnings we've gathered for the given block.
flushWarnings(const BlockDecl * Block,Sema & S)1657*e038c9c4Sjoerg   void flushWarnings(const BlockDecl *Block, Sema &S) {
1658*e038c9c4Sjoerg     for (const PartialDiagnosticAt &Delayed : DelayedBlockWarnings[Block])
1659*e038c9c4Sjoerg       S.Diag(Delayed.first, Delayed.second);
1660*e038c9c4Sjoerg 
1661*e038c9c4Sjoerg     discardWarnings(Block);
1662*e038c9c4Sjoerg   }
1663*e038c9c4Sjoerg   // Discard all of the warnings we've gathered for the given block.
discardWarnings(const BlockDecl * Block)1664*e038c9c4Sjoerg   void discardWarnings(const BlockDecl *Block) {
1665*e038c9c4Sjoerg     DelayedBlockWarnings.erase(Block);
1666*e038c9c4Sjoerg   }
1667*e038c9c4Sjoerg 
1668*e038c9c4Sjoerg private:
1669*e038c9c4Sjoerg   using DelayedDiagnostics = SmallVector<PartialDiagnosticAt, 2>;
1670*e038c9c4Sjoerg   llvm::DenseMap<const BlockDecl *, DelayedDiagnostics> DelayedBlockWarnings;
16717330f729Sjoerg };
1672*e038c9c4Sjoerg 
1673*e038c9c4Sjoerg class CalledOnceCheckReporter : public CalledOnceCheckHandler {
1674*e038c9c4Sjoerg public:
CalledOnceCheckReporter(Sema & S,CalledOnceInterProceduralData & Data)1675*e038c9c4Sjoerg   CalledOnceCheckReporter(Sema &S, CalledOnceInterProceduralData &Data)
1676*e038c9c4Sjoerg       : S(S), Data(Data) {}
handleDoubleCall(const ParmVarDecl * Parameter,const Expr * Call,const Expr * PrevCall,bool IsCompletionHandler,bool Poised)1677*e038c9c4Sjoerg   void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call,
1678*e038c9c4Sjoerg                         const Expr *PrevCall, bool IsCompletionHandler,
1679*e038c9c4Sjoerg                         bool Poised) override {
1680*e038c9c4Sjoerg     auto DiagToReport = IsCompletionHandler
1681*e038c9c4Sjoerg                             ? diag::warn_completion_handler_called_twice
1682*e038c9c4Sjoerg                             : diag::warn_called_once_gets_called_twice;
1683*e038c9c4Sjoerg     S.Diag(Call->getBeginLoc(), DiagToReport) << Parameter;
1684*e038c9c4Sjoerg     S.Diag(PrevCall->getBeginLoc(), diag::note_called_once_gets_called_twice)
1685*e038c9c4Sjoerg         << Poised;
1686*e038c9c4Sjoerg   }
1687*e038c9c4Sjoerg 
handleNeverCalled(const ParmVarDecl * Parameter,bool IsCompletionHandler)1688*e038c9c4Sjoerg   void handleNeverCalled(const ParmVarDecl *Parameter,
1689*e038c9c4Sjoerg                          bool IsCompletionHandler) override {
1690*e038c9c4Sjoerg     auto DiagToReport = IsCompletionHandler
1691*e038c9c4Sjoerg                             ? diag::warn_completion_handler_never_called
1692*e038c9c4Sjoerg                             : diag::warn_called_once_never_called;
1693*e038c9c4Sjoerg     S.Diag(Parameter->getBeginLoc(), DiagToReport)
1694*e038c9c4Sjoerg         << Parameter << /* Captured */ false;
1695*e038c9c4Sjoerg   }
1696*e038c9c4Sjoerg 
handleNeverCalled(const ParmVarDecl * Parameter,const Decl * Function,const Stmt * Where,NeverCalledReason Reason,bool IsCalledDirectly,bool IsCompletionHandler)1697*e038c9c4Sjoerg   void handleNeverCalled(const ParmVarDecl *Parameter, const Decl *Function,
1698*e038c9c4Sjoerg                          const Stmt *Where, NeverCalledReason Reason,
1699*e038c9c4Sjoerg                          bool IsCalledDirectly,
1700*e038c9c4Sjoerg                          bool IsCompletionHandler) override {
1701*e038c9c4Sjoerg     auto DiagToReport = IsCompletionHandler
1702*e038c9c4Sjoerg                             ? diag::warn_completion_handler_never_called_when
1703*e038c9c4Sjoerg                             : diag::warn_called_once_never_called_when;
1704*e038c9c4Sjoerg     PartialDiagnosticAt Warning(Where->getBeginLoc(), S.PDiag(DiagToReport)
1705*e038c9c4Sjoerg                                                           << Parameter
1706*e038c9c4Sjoerg                                                           << IsCalledDirectly
1707*e038c9c4Sjoerg                                                           << (unsigned)Reason);
1708*e038c9c4Sjoerg 
1709*e038c9c4Sjoerg     if (const auto *Block = dyn_cast<BlockDecl>(Function)) {
1710*e038c9c4Sjoerg       // We shouldn't report these warnings on blocks immediately
1711*e038c9c4Sjoerg       Data.addDelayedWarning(Block, std::move(Warning));
1712*e038c9c4Sjoerg     } else {
1713*e038c9c4Sjoerg       S.Diag(Warning.first, Warning.second);
1714*e038c9c4Sjoerg     }
1715*e038c9c4Sjoerg   }
1716*e038c9c4Sjoerg 
handleCapturedNeverCalled(const ParmVarDecl * Parameter,const Decl * Where,bool IsCompletionHandler)1717*e038c9c4Sjoerg   void handleCapturedNeverCalled(const ParmVarDecl *Parameter,
1718*e038c9c4Sjoerg                                  const Decl *Where,
1719*e038c9c4Sjoerg                                  bool IsCompletionHandler) override {
1720*e038c9c4Sjoerg     auto DiagToReport = IsCompletionHandler
1721*e038c9c4Sjoerg                             ? diag::warn_completion_handler_never_called
1722*e038c9c4Sjoerg                             : diag::warn_called_once_never_called;
1723*e038c9c4Sjoerg     S.Diag(Where->getBeginLoc(), DiagToReport)
1724*e038c9c4Sjoerg         << Parameter << /* Captured */ true;
1725*e038c9c4Sjoerg   }
1726*e038c9c4Sjoerg 
1727*e038c9c4Sjoerg   void
handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl * Block)1728*e038c9c4Sjoerg   handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl *Block) override {
1729*e038c9c4Sjoerg     Data.flushWarnings(Block, S);
1730*e038c9c4Sjoerg   }
1731*e038c9c4Sjoerg 
handleBlockWithNoGuarantees(const BlockDecl * Block)1732*e038c9c4Sjoerg   void handleBlockWithNoGuarantees(const BlockDecl *Block) override {
1733*e038c9c4Sjoerg     Data.discardWarnings(Block);
1734*e038c9c4Sjoerg   }
1735*e038c9c4Sjoerg 
1736*e038c9c4Sjoerg private:
1737*e038c9c4Sjoerg   Sema &S;
1738*e038c9c4Sjoerg   CalledOnceInterProceduralData &Data;
1739*e038c9c4Sjoerg };
1740*e038c9c4Sjoerg 
1741*e038c9c4Sjoerg constexpr unsigned CalledOnceWarnings[] = {
1742*e038c9c4Sjoerg     diag::warn_called_once_never_called,
1743*e038c9c4Sjoerg     diag::warn_called_once_never_called_when,
1744*e038c9c4Sjoerg     diag::warn_called_once_gets_called_twice};
1745*e038c9c4Sjoerg 
1746*e038c9c4Sjoerg constexpr unsigned CompletionHandlerWarnings[]{
1747*e038c9c4Sjoerg     diag::warn_completion_handler_never_called,
1748*e038c9c4Sjoerg     diag::warn_completion_handler_never_called_when,
1749*e038c9c4Sjoerg     diag::warn_completion_handler_called_twice};
1750*e038c9c4Sjoerg 
shouldAnalyzeCalledOnceImpl(llvm::ArrayRef<unsigned> DiagIDs,const DiagnosticsEngine & Diags,SourceLocation At)1751*e038c9c4Sjoerg bool shouldAnalyzeCalledOnceImpl(llvm::ArrayRef<unsigned> DiagIDs,
1752*e038c9c4Sjoerg                                  const DiagnosticsEngine &Diags,
1753*e038c9c4Sjoerg                                  SourceLocation At) {
1754*e038c9c4Sjoerg   return llvm::any_of(DiagIDs, [&Diags, At](unsigned DiagID) {
1755*e038c9c4Sjoerg     return !Diags.isIgnored(DiagID, At);
1756*e038c9c4Sjoerg   });
1757*e038c9c4Sjoerg }
1758*e038c9c4Sjoerg 
shouldAnalyzeCalledOnceConventions(const DiagnosticsEngine & Diags,SourceLocation At)1759*e038c9c4Sjoerg bool shouldAnalyzeCalledOnceConventions(const DiagnosticsEngine &Diags,
1760*e038c9c4Sjoerg                                         SourceLocation At) {
1761*e038c9c4Sjoerg   return shouldAnalyzeCalledOnceImpl(CompletionHandlerWarnings, Diags, At);
1762*e038c9c4Sjoerg }
1763*e038c9c4Sjoerg 
shouldAnalyzeCalledOnceParameters(const DiagnosticsEngine & Diags,SourceLocation At)1764*e038c9c4Sjoerg bool shouldAnalyzeCalledOnceParameters(const DiagnosticsEngine &Diags,
1765*e038c9c4Sjoerg                                        SourceLocation At) {
1766*e038c9c4Sjoerg   return shouldAnalyzeCalledOnceImpl(CalledOnceWarnings, Diags, At) ||
1767*e038c9c4Sjoerg          shouldAnalyzeCalledOnceConventions(Diags, At);
1768*e038c9c4Sjoerg }
17697330f729Sjoerg } // anonymous namespace
17707330f729Sjoerg 
17717330f729Sjoerg //===----------------------------------------------------------------------===//
17727330f729Sjoerg // -Wthread-safety
17737330f729Sjoerg //===----------------------------------------------------------------------===//
17747330f729Sjoerg namespace clang {
17757330f729Sjoerg namespace threadSafety {
17767330f729Sjoerg namespace {
17777330f729Sjoerg class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
17787330f729Sjoerg   Sema &S;
17797330f729Sjoerg   DiagList Warnings;
17807330f729Sjoerg   SourceLocation FunLocation, FunEndLocation;
17817330f729Sjoerg 
17827330f729Sjoerg   const FunctionDecl *CurrentFunction;
17837330f729Sjoerg   bool Verbose;
17847330f729Sjoerg 
getNotes() const17857330f729Sjoerg   OptionalNotes getNotes() const {
17867330f729Sjoerg     if (Verbose && CurrentFunction) {
17877330f729Sjoerg       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
17887330f729Sjoerg                                 S.PDiag(diag::note_thread_warning_in_fun)
17897330f729Sjoerg                                     << CurrentFunction);
17907330f729Sjoerg       return OptionalNotes(1, FNote);
17917330f729Sjoerg     }
17927330f729Sjoerg     return OptionalNotes();
17937330f729Sjoerg   }
17947330f729Sjoerg 
getNotes(const PartialDiagnosticAt & Note) const17957330f729Sjoerg   OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
17967330f729Sjoerg     OptionalNotes ONS(1, Note);
17977330f729Sjoerg     if (Verbose && CurrentFunction) {
17987330f729Sjoerg       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
17997330f729Sjoerg                                 S.PDiag(diag::note_thread_warning_in_fun)
18007330f729Sjoerg                                     << CurrentFunction);
18017330f729Sjoerg       ONS.push_back(std::move(FNote));
18027330f729Sjoerg     }
18037330f729Sjoerg     return ONS;
18047330f729Sjoerg   }
18057330f729Sjoerg 
getNotes(const PartialDiagnosticAt & Note1,const PartialDiagnosticAt & Note2) const18067330f729Sjoerg   OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
18077330f729Sjoerg                          const PartialDiagnosticAt &Note2) const {
18087330f729Sjoerg     OptionalNotes ONS;
18097330f729Sjoerg     ONS.push_back(Note1);
18107330f729Sjoerg     ONS.push_back(Note2);
18117330f729Sjoerg     if (Verbose && CurrentFunction) {
18127330f729Sjoerg       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
18137330f729Sjoerg                                 S.PDiag(diag::note_thread_warning_in_fun)
18147330f729Sjoerg                                     << CurrentFunction);
18157330f729Sjoerg       ONS.push_back(std::move(FNote));
18167330f729Sjoerg     }
18177330f729Sjoerg     return ONS;
18187330f729Sjoerg   }
18197330f729Sjoerg 
makeLockedHereNote(SourceLocation LocLocked,StringRef Kind)18207330f729Sjoerg   OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
18217330f729Sjoerg     return LocLocked.isValid()
18227330f729Sjoerg                ? getNotes(PartialDiagnosticAt(
18237330f729Sjoerg                      LocLocked, S.PDiag(diag::note_locked_here) << Kind))
18247330f729Sjoerg                : getNotes();
18257330f729Sjoerg   }
18267330f729Sjoerg 
makeUnlockedHereNote(SourceLocation LocUnlocked,StringRef Kind)1827*e038c9c4Sjoerg   OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked,
1828*e038c9c4Sjoerg                                      StringRef Kind) {
1829*e038c9c4Sjoerg     return LocUnlocked.isValid()
1830*e038c9c4Sjoerg                ? getNotes(PartialDiagnosticAt(
1831*e038c9c4Sjoerg                      LocUnlocked, S.PDiag(diag::note_unlocked_here) << Kind))
1832*e038c9c4Sjoerg                : getNotes();
1833*e038c9c4Sjoerg   }
1834*e038c9c4Sjoerg 
18357330f729Sjoerg  public:
ThreadSafetyReporter(Sema & S,SourceLocation FL,SourceLocation FEL)18367330f729Sjoerg   ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
18377330f729Sjoerg     : S(S), FunLocation(FL), FunEndLocation(FEL),
18387330f729Sjoerg       CurrentFunction(nullptr), Verbose(false) {}
18397330f729Sjoerg 
setVerbose(bool b)18407330f729Sjoerg   void setVerbose(bool b) { Verbose = b; }
18417330f729Sjoerg 
18427330f729Sjoerg   /// Emit all buffered diagnostics in order of sourcelocation.
18437330f729Sjoerg   /// We need to output diagnostics produced while iterating through
18447330f729Sjoerg   /// the lockset in deterministic order, so this function orders diagnostics
18457330f729Sjoerg   /// and outputs them.
emitDiagnostics()18467330f729Sjoerg   void emitDiagnostics() {
18477330f729Sjoerg     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
18487330f729Sjoerg     for (const auto &Diag : Warnings) {
18497330f729Sjoerg       S.Diag(Diag.first.first, Diag.first.second);
18507330f729Sjoerg       for (const auto &Note : Diag.second)
18517330f729Sjoerg         S.Diag(Note.first, Note.second);
18527330f729Sjoerg     }
18537330f729Sjoerg   }
18547330f729Sjoerg 
handleInvalidLockExp(StringRef Kind,SourceLocation Loc)18557330f729Sjoerg   void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
18567330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
18577330f729Sjoerg                                          << Loc);
18587330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
18597330f729Sjoerg   }
18607330f729Sjoerg 
handleUnmatchedUnlock(StringRef Kind,Name LockName,SourceLocation Loc,SourceLocation LocPreviousUnlock)1861*e038c9c4Sjoerg   void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc,
1862*e038c9c4Sjoerg                              SourceLocation LocPreviousUnlock) override {
18637330f729Sjoerg     if (Loc.isInvalid())
18647330f729Sjoerg       Loc = FunLocation;
18657330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock)
18667330f729Sjoerg                                          << Kind << LockName);
1867*e038c9c4Sjoerg     Warnings.emplace_back(std::move(Warning),
1868*e038c9c4Sjoerg                           makeUnlockedHereNote(LocPreviousUnlock, Kind));
18697330f729Sjoerg   }
18707330f729Sjoerg 
handleIncorrectUnlockKind(StringRef Kind,Name LockName,LockKind Expected,LockKind Received,SourceLocation LocLocked,SourceLocation LocUnlock)18717330f729Sjoerg   void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
18727330f729Sjoerg                                  LockKind Expected, LockKind Received,
18737330f729Sjoerg                                  SourceLocation LocLocked,
18747330f729Sjoerg                                  SourceLocation LocUnlock) override {
18757330f729Sjoerg     if (LocUnlock.isInvalid())
18767330f729Sjoerg       LocUnlock = FunLocation;
18777330f729Sjoerg     PartialDiagnosticAt Warning(
18787330f729Sjoerg         LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch)
18797330f729Sjoerg                        << Kind << LockName << Received << Expected);
18807330f729Sjoerg     Warnings.emplace_back(std::move(Warning),
18817330f729Sjoerg                           makeLockedHereNote(LocLocked, Kind));
18827330f729Sjoerg   }
18837330f729Sjoerg 
handleDoubleLock(StringRef Kind,Name LockName,SourceLocation LocLocked,SourceLocation LocDoubleLock)18847330f729Sjoerg   void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
18857330f729Sjoerg                         SourceLocation LocDoubleLock) override {
18867330f729Sjoerg     if (LocDoubleLock.isInvalid())
18877330f729Sjoerg       LocDoubleLock = FunLocation;
18887330f729Sjoerg     PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock)
18897330f729Sjoerg                                                    << Kind << LockName);
18907330f729Sjoerg     Warnings.emplace_back(std::move(Warning),
18917330f729Sjoerg                           makeLockedHereNote(LocLocked, Kind));
18927330f729Sjoerg   }
18937330f729Sjoerg 
handleMutexHeldEndOfScope(StringRef Kind,Name LockName,SourceLocation LocLocked,SourceLocation LocEndOfScope,LockErrorKind LEK)18947330f729Sjoerg   void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
18957330f729Sjoerg                                  SourceLocation LocLocked,
18967330f729Sjoerg                                  SourceLocation LocEndOfScope,
18977330f729Sjoerg                                  LockErrorKind LEK) override {
18987330f729Sjoerg     unsigned DiagID = 0;
18997330f729Sjoerg     switch (LEK) {
19007330f729Sjoerg       case LEK_LockedSomePredecessors:
19017330f729Sjoerg         DiagID = diag::warn_lock_some_predecessors;
19027330f729Sjoerg         break;
19037330f729Sjoerg       case LEK_LockedSomeLoopIterations:
19047330f729Sjoerg         DiagID = diag::warn_expecting_lock_held_on_loop;
19057330f729Sjoerg         break;
19067330f729Sjoerg       case LEK_LockedAtEndOfFunction:
19077330f729Sjoerg         DiagID = diag::warn_no_unlock;
19087330f729Sjoerg         break;
19097330f729Sjoerg       case LEK_NotLockedAtEndOfFunction:
19107330f729Sjoerg         DiagID = diag::warn_expecting_locked;
19117330f729Sjoerg         break;
19127330f729Sjoerg     }
19137330f729Sjoerg     if (LocEndOfScope.isInvalid())
19147330f729Sjoerg       LocEndOfScope = FunEndLocation;
19157330f729Sjoerg 
19167330f729Sjoerg     PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
19177330f729Sjoerg                                                                << LockName);
19187330f729Sjoerg     Warnings.emplace_back(std::move(Warning),
19197330f729Sjoerg                           makeLockedHereNote(LocLocked, Kind));
19207330f729Sjoerg   }
19217330f729Sjoerg 
handleExclusiveAndShared(StringRef Kind,Name LockName,SourceLocation Loc1,SourceLocation Loc2)19227330f729Sjoerg   void handleExclusiveAndShared(StringRef Kind, Name LockName,
19237330f729Sjoerg                                 SourceLocation Loc1,
19247330f729Sjoerg                                 SourceLocation Loc2) override {
19257330f729Sjoerg     PartialDiagnosticAt Warning(Loc1,
19267330f729Sjoerg                                 S.PDiag(diag::warn_lock_exclusive_and_shared)
19277330f729Sjoerg                                     << Kind << LockName);
19287330f729Sjoerg     PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
19297330f729Sjoerg                                        << Kind << LockName);
19307330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes(Note));
19317330f729Sjoerg   }
19327330f729Sjoerg 
handleNoMutexHeld(StringRef Kind,const NamedDecl * D,ProtectedOperationKind POK,AccessKind AK,SourceLocation Loc)19337330f729Sjoerg   void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
19347330f729Sjoerg                          ProtectedOperationKind POK, AccessKind AK,
19357330f729Sjoerg                          SourceLocation Loc) override {
19367330f729Sjoerg     assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
19377330f729Sjoerg            "Only works for variables");
19387330f729Sjoerg     unsigned DiagID = POK == POK_VarAccess?
19397330f729Sjoerg                         diag::warn_variable_requires_any_lock:
19407330f729Sjoerg                         diag::warn_var_deref_requires_any_lock;
19417330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
19427330f729Sjoerg       << D << getLockKindFromAccessKind(AK));
19437330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
19447330f729Sjoerg   }
19457330f729Sjoerg 
handleMutexNotHeld(StringRef Kind,const NamedDecl * D,ProtectedOperationKind POK,Name LockName,LockKind LK,SourceLocation Loc,Name * PossibleMatch)19467330f729Sjoerg   void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
19477330f729Sjoerg                           ProtectedOperationKind POK, Name LockName,
19487330f729Sjoerg                           LockKind LK, SourceLocation Loc,
19497330f729Sjoerg                           Name *PossibleMatch) override {
19507330f729Sjoerg     unsigned DiagID = 0;
19517330f729Sjoerg     if (PossibleMatch) {
19527330f729Sjoerg       switch (POK) {
19537330f729Sjoerg         case POK_VarAccess:
19547330f729Sjoerg           DiagID = diag::warn_variable_requires_lock_precise;
19557330f729Sjoerg           break;
19567330f729Sjoerg         case POK_VarDereference:
19577330f729Sjoerg           DiagID = diag::warn_var_deref_requires_lock_precise;
19587330f729Sjoerg           break;
19597330f729Sjoerg         case POK_FunctionCall:
19607330f729Sjoerg           DiagID = diag::warn_fun_requires_lock_precise;
19617330f729Sjoerg           break;
19627330f729Sjoerg         case POK_PassByRef:
19637330f729Sjoerg           DiagID = diag::warn_guarded_pass_by_reference;
19647330f729Sjoerg           break;
19657330f729Sjoerg         case POK_PtPassByRef:
19667330f729Sjoerg           DiagID = diag::warn_pt_guarded_pass_by_reference;
19677330f729Sjoerg           break;
19687330f729Sjoerg       }
19697330f729Sjoerg       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
19707330f729Sjoerg                                                        << D
19717330f729Sjoerg                                                        << LockName << LK);
19727330f729Sjoerg       PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
19737330f729Sjoerg                                         << *PossibleMatch);
19747330f729Sjoerg       if (Verbose && POK == POK_VarAccess) {
19757330f729Sjoerg         PartialDiagnosticAt VNote(D->getLocation(),
19767330f729Sjoerg                                   S.PDiag(diag::note_guarded_by_declared_here)
1977*e038c9c4Sjoerg                                       << D->getDeclName());
19787330f729Sjoerg         Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
19797330f729Sjoerg       } else
19807330f729Sjoerg         Warnings.emplace_back(std::move(Warning), getNotes(Note));
19817330f729Sjoerg     } else {
19827330f729Sjoerg       switch (POK) {
19837330f729Sjoerg         case POK_VarAccess:
19847330f729Sjoerg           DiagID = diag::warn_variable_requires_lock;
19857330f729Sjoerg           break;
19867330f729Sjoerg         case POK_VarDereference:
19877330f729Sjoerg           DiagID = diag::warn_var_deref_requires_lock;
19887330f729Sjoerg           break;
19897330f729Sjoerg         case POK_FunctionCall:
19907330f729Sjoerg           DiagID = diag::warn_fun_requires_lock;
19917330f729Sjoerg           break;
19927330f729Sjoerg         case POK_PassByRef:
19937330f729Sjoerg           DiagID = diag::warn_guarded_pass_by_reference;
19947330f729Sjoerg           break;
19957330f729Sjoerg         case POK_PtPassByRef:
19967330f729Sjoerg           DiagID = diag::warn_pt_guarded_pass_by_reference;
19977330f729Sjoerg           break;
19987330f729Sjoerg       }
19997330f729Sjoerg       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
20007330f729Sjoerg                                                        << D
20017330f729Sjoerg                                                        << LockName << LK);
20027330f729Sjoerg       if (Verbose && POK == POK_VarAccess) {
20037330f729Sjoerg         PartialDiagnosticAt Note(D->getLocation(),
20047330f729Sjoerg                                  S.PDiag(diag::note_guarded_by_declared_here));
20057330f729Sjoerg         Warnings.emplace_back(std::move(Warning), getNotes(Note));
20067330f729Sjoerg       } else
20077330f729Sjoerg         Warnings.emplace_back(std::move(Warning), getNotes());
20087330f729Sjoerg     }
20097330f729Sjoerg   }
20107330f729Sjoerg 
handleNegativeNotHeld(StringRef Kind,Name LockName,Name Neg,SourceLocation Loc)20117330f729Sjoerg   void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
20127330f729Sjoerg                              SourceLocation Loc) override {
20137330f729Sjoerg     PartialDiagnosticAt Warning(Loc,
20147330f729Sjoerg         S.PDiag(diag::warn_acquire_requires_negative_cap)
20157330f729Sjoerg         << Kind << LockName << Neg);
20167330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
20177330f729Sjoerg   }
20187330f729Sjoerg 
handleNegativeNotHeld(const NamedDecl * D,Name LockName,SourceLocation Loc)2019*e038c9c4Sjoerg   void handleNegativeNotHeld(const NamedDecl *D, Name LockName,
2020*e038c9c4Sjoerg                              SourceLocation Loc) override {
2021*e038c9c4Sjoerg     PartialDiagnosticAt Warning(
2022*e038c9c4Sjoerg         Loc, S.PDiag(diag::warn_fun_requires_negative_cap) << D << LockName);
2023*e038c9c4Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
2024*e038c9c4Sjoerg   }
2025*e038c9c4Sjoerg 
handleFunExcludesLock(StringRef Kind,Name FunName,Name LockName,SourceLocation Loc)20267330f729Sjoerg   void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
20277330f729Sjoerg                              SourceLocation Loc) override {
20287330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
20297330f729Sjoerg                                          << Kind << FunName << LockName);
20307330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
20317330f729Sjoerg   }
20327330f729Sjoerg 
handleLockAcquiredBefore(StringRef Kind,Name L1Name,Name L2Name,SourceLocation Loc)20337330f729Sjoerg   void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
20347330f729Sjoerg                                 SourceLocation Loc) override {
20357330f729Sjoerg     PartialDiagnosticAt Warning(Loc,
20367330f729Sjoerg       S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
20377330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
20387330f729Sjoerg   }
20397330f729Sjoerg 
handleBeforeAfterCycle(Name L1Name,SourceLocation Loc)20407330f729Sjoerg   void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
20417330f729Sjoerg     PartialDiagnosticAt Warning(Loc,
20427330f729Sjoerg       S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
20437330f729Sjoerg     Warnings.emplace_back(std::move(Warning), getNotes());
20447330f729Sjoerg   }
20457330f729Sjoerg 
enterFunction(const FunctionDecl * FD)20467330f729Sjoerg   void enterFunction(const FunctionDecl* FD) override {
20477330f729Sjoerg     CurrentFunction = FD;
20487330f729Sjoerg   }
20497330f729Sjoerg 
leaveFunction(const FunctionDecl * FD)20507330f729Sjoerg   void leaveFunction(const FunctionDecl* FD) override {
20517330f729Sjoerg     CurrentFunction = nullptr;
20527330f729Sjoerg   }
20537330f729Sjoerg };
20547330f729Sjoerg } // anonymous namespace
20557330f729Sjoerg } // namespace threadSafety
20567330f729Sjoerg } // namespace clang
20577330f729Sjoerg 
20587330f729Sjoerg //===----------------------------------------------------------------------===//
20597330f729Sjoerg // -Wconsumed
20607330f729Sjoerg //===----------------------------------------------------------------------===//
20617330f729Sjoerg 
20627330f729Sjoerg namespace clang {
20637330f729Sjoerg namespace consumed {
20647330f729Sjoerg namespace {
20657330f729Sjoerg class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
20667330f729Sjoerg 
20677330f729Sjoerg   Sema &S;
20687330f729Sjoerg   DiagList Warnings;
20697330f729Sjoerg 
20707330f729Sjoerg public:
20717330f729Sjoerg 
ConsumedWarningsHandler(Sema & S)20727330f729Sjoerg   ConsumedWarningsHandler(Sema &S) : S(S) {}
20737330f729Sjoerg 
emitDiagnostics()20747330f729Sjoerg   void emitDiagnostics() override {
20757330f729Sjoerg     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
20767330f729Sjoerg     for (const auto &Diag : Warnings) {
20777330f729Sjoerg       S.Diag(Diag.first.first, Diag.first.second);
20787330f729Sjoerg       for (const auto &Note : Diag.second)
20797330f729Sjoerg         S.Diag(Note.first, Note.second);
20807330f729Sjoerg     }
20817330f729Sjoerg   }
20827330f729Sjoerg 
warnLoopStateMismatch(SourceLocation Loc,StringRef VariableName)20837330f729Sjoerg   void warnLoopStateMismatch(SourceLocation Loc,
20847330f729Sjoerg                              StringRef VariableName) override {
20857330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
20867330f729Sjoerg       VariableName);
20877330f729Sjoerg 
20887330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
20897330f729Sjoerg   }
20907330f729Sjoerg 
warnParamReturnTypestateMismatch(SourceLocation Loc,StringRef VariableName,StringRef ExpectedState,StringRef ObservedState)20917330f729Sjoerg   void warnParamReturnTypestateMismatch(SourceLocation Loc,
20927330f729Sjoerg                                         StringRef VariableName,
20937330f729Sjoerg                                         StringRef ExpectedState,
20947330f729Sjoerg                                         StringRef ObservedState) override {
20957330f729Sjoerg 
20967330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(
20977330f729Sjoerg       diag::warn_param_return_typestate_mismatch) << VariableName <<
20987330f729Sjoerg         ExpectedState << ObservedState);
20997330f729Sjoerg 
21007330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21017330f729Sjoerg   }
21027330f729Sjoerg 
warnParamTypestateMismatch(SourceLocation Loc,StringRef ExpectedState,StringRef ObservedState)21037330f729Sjoerg   void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
21047330f729Sjoerg                                   StringRef ObservedState) override {
21057330f729Sjoerg 
21067330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(
21077330f729Sjoerg       diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
21087330f729Sjoerg 
21097330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21107330f729Sjoerg   }
21117330f729Sjoerg 
warnReturnTypestateForUnconsumableType(SourceLocation Loc,StringRef TypeName)21127330f729Sjoerg   void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
21137330f729Sjoerg                                               StringRef TypeName) override {
21147330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(
21157330f729Sjoerg       diag::warn_return_typestate_for_unconsumable_type) << TypeName);
21167330f729Sjoerg 
21177330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21187330f729Sjoerg   }
21197330f729Sjoerg 
warnReturnTypestateMismatch(SourceLocation Loc,StringRef ExpectedState,StringRef ObservedState)21207330f729Sjoerg   void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
21217330f729Sjoerg                                    StringRef ObservedState) override {
21227330f729Sjoerg 
21237330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(
21247330f729Sjoerg       diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
21257330f729Sjoerg 
21267330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21277330f729Sjoerg   }
21287330f729Sjoerg 
warnUseOfTempInInvalidState(StringRef MethodName,StringRef State,SourceLocation Loc)21297330f729Sjoerg   void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
21307330f729Sjoerg                                    SourceLocation Loc) override {
21317330f729Sjoerg 
21327330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(
21337330f729Sjoerg       diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
21347330f729Sjoerg 
21357330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21367330f729Sjoerg   }
21377330f729Sjoerg 
warnUseInInvalidState(StringRef MethodName,StringRef VariableName,StringRef State,SourceLocation Loc)21387330f729Sjoerg   void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
21397330f729Sjoerg                              StringRef State, SourceLocation Loc) override {
21407330f729Sjoerg 
21417330f729Sjoerg     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
21427330f729Sjoerg                                 MethodName << VariableName << State);
21437330f729Sjoerg 
21447330f729Sjoerg     Warnings.emplace_back(std::move(Warning), OptionalNotes());
21457330f729Sjoerg   }
21467330f729Sjoerg };
21477330f729Sjoerg } // anonymous namespace
21487330f729Sjoerg } // namespace consumed
21497330f729Sjoerg } // namespace clang
21507330f729Sjoerg 
21517330f729Sjoerg //===----------------------------------------------------------------------===//
21527330f729Sjoerg // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
21537330f729Sjoerg //  warnings on a function, method, or block.
21547330f729Sjoerg //===----------------------------------------------------------------------===//
21557330f729Sjoerg 
Policy()2156*e038c9c4Sjoerg sema::AnalysisBasedWarnings::Policy::Policy() {
21577330f729Sjoerg   enableCheckFallThrough = 1;
21587330f729Sjoerg   enableCheckUnreachable = 0;
21597330f729Sjoerg   enableThreadSafetyAnalysis = 0;
21607330f729Sjoerg   enableConsumedAnalysis = 0;
21617330f729Sjoerg }
21627330f729Sjoerg 
2163*e038c9c4Sjoerg /// InterProceduralData aims to be a storage of whatever data should be passed
2164*e038c9c4Sjoerg /// between analyses of different functions.
2165*e038c9c4Sjoerg ///
2166*e038c9c4Sjoerg /// At the moment, its primary goal is to make the information gathered during
2167*e038c9c4Sjoerg /// the analysis of the blocks available during the analysis of the enclosing
2168*e038c9c4Sjoerg /// function.  This is important due to the fact that blocks are analyzed before
2169*e038c9c4Sjoerg /// the enclosed function is even parsed fully, so it is not viable to access
2170*e038c9c4Sjoerg /// anything in the outer scope while analyzing the block.  On the other hand,
2171*e038c9c4Sjoerg /// re-building CFG for blocks and re-analyzing them when we do have all the
2172*e038c9c4Sjoerg /// information (i.e. during the analysis of the enclosing function) seems to be
2173*e038c9c4Sjoerg /// ill-designed.
2174*e038c9c4Sjoerg class sema::AnalysisBasedWarnings::InterProceduralData {
2175*e038c9c4Sjoerg public:
2176*e038c9c4Sjoerg   // It is important to analyze blocks within functions because it's a very
2177*e038c9c4Sjoerg   // common pattern to capture completion handler parameters by blocks.
2178*e038c9c4Sjoerg   CalledOnceInterProceduralData CalledOnceData;
2179*e038c9c4Sjoerg };
2180*e038c9c4Sjoerg 
isEnabled(DiagnosticsEngine & D,unsigned diag)21817330f729Sjoerg static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
21827330f729Sjoerg   return (unsigned)!D.isIgnored(diag, SourceLocation());
21837330f729Sjoerg }
21847330f729Sjoerg 
AnalysisBasedWarnings(Sema & s)2185*e038c9c4Sjoerg sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2186*e038c9c4Sjoerg     : S(s), IPData(std::make_unique<InterProceduralData>()),
2187*e038c9c4Sjoerg       NumFunctionsAnalyzed(0), NumFunctionsWithBadCFGs(0), NumCFGBlocks(0),
2188*e038c9c4Sjoerg       MaxCFGBlocksPerFunction(0), NumUninitAnalysisFunctions(0),
2189*e038c9c4Sjoerg       NumUninitAnalysisVariables(0), MaxUninitAnalysisVariablesPerFunction(0),
21907330f729Sjoerg       NumUninitAnalysisBlockVisits(0),
21917330f729Sjoerg       MaxUninitAnalysisBlockVisitsPerFunction(0) {
21927330f729Sjoerg 
21937330f729Sjoerg   using namespace diag;
21947330f729Sjoerg   DiagnosticsEngine &D = S.getDiagnostics();
21957330f729Sjoerg 
21967330f729Sjoerg   DefaultPolicy.enableCheckUnreachable =
2197*e038c9c4Sjoerg       isEnabled(D, warn_unreachable) || isEnabled(D, warn_unreachable_break) ||
21987330f729Sjoerg       isEnabled(D, warn_unreachable_return) ||
21997330f729Sjoerg       isEnabled(D, warn_unreachable_loop_increment);
22007330f729Sjoerg 
2201*e038c9c4Sjoerg   DefaultPolicy.enableThreadSafetyAnalysis = isEnabled(D, warn_double_lock);
22027330f729Sjoerg 
22037330f729Sjoerg   DefaultPolicy.enableConsumedAnalysis =
22047330f729Sjoerg       isEnabled(D, warn_use_in_invalid_state);
22057330f729Sjoerg }
22067330f729Sjoerg 
2207*e038c9c4Sjoerg // We need this here for unique_ptr with forward declared class.
2208*e038c9c4Sjoerg sema::AnalysisBasedWarnings::~AnalysisBasedWarnings() = default;
2209*e038c9c4Sjoerg 
flushDiagnostics(Sema & S,const sema::FunctionScopeInfo * fscope)22107330f729Sjoerg static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
22117330f729Sjoerg   for (const auto &D : fscope->PossiblyUnreachableDiags)
22127330f729Sjoerg     S.Diag(D.Loc, D.PD);
22137330f729Sjoerg }
22147330f729Sjoerg 
IssueWarnings(sema::AnalysisBasedWarnings::Policy P,sema::FunctionScopeInfo * fscope,const Decl * D,QualType BlockType)2215*e038c9c4Sjoerg void clang::sema::AnalysisBasedWarnings::IssueWarnings(
2216*e038c9c4Sjoerg     sema::AnalysisBasedWarnings::Policy P, sema::FunctionScopeInfo *fscope,
22177330f729Sjoerg     const Decl *D, QualType BlockType) {
22187330f729Sjoerg 
22197330f729Sjoerg   // We avoid doing analysis-based warnings when there are errors for
22207330f729Sjoerg   // two reasons:
22217330f729Sjoerg   // (1) The CFGs often can't be constructed (if the body is invalid), so
22227330f729Sjoerg   //     don't bother trying.
22237330f729Sjoerg   // (2) The code already has problems; running the analysis just takes more
22247330f729Sjoerg   //     time.
22257330f729Sjoerg   DiagnosticsEngine &Diags = S.getDiagnostics();
22267330f729Sjoerg 
22277330f729Sjoerg   // Do not do any analysis if we are going to just ignore them.
22287330f729Sjoerg   if (Diags.getIgnoreAllWarnings() ||
22297330f729Sjoerg       (Diags.getSuppressSystemWarnings() &&
22307330f729Sjoerg        S.SourceMgr.isInSystemHeader(D->getLocation())))
22317330f729Sjoerg     return;
22327330f729Sjoerg 
22337330f729Sjoerg   // For code in dependent contexts, we'll do this at instantiation time.
22347330f729Sjoerg   if (cast<DeclContext>(D)->isDependentContext())
22357330f729Sjoerg     return;
22367330f729Sjoerg 
2237*e038c9c4Sjoerg   if (S.hasUncompilableErrorOccurred()) {
22387330f729Sjoerg     // Flush out any possibly unreachable diagnostics.
22397330f729Sjoerg     flushDiagnostics(S, fscope);
22407330f729Sjoerg     return;
22417330f729Sjoerg   }
22427330f729Sjoerg 
22437330f729Sjoerg   const Stmt *Body = D->getBody();
22447330f729Sjoerg   assert(Body);
22457330f729Sjoerg 
22467330f729Sjoerg   // Construct the analysis context with the specified CFG build options.
22477330f729Sjoerg   AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
22487330f729Sjoerg 
22497330f729Sjoerg   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
22507330f729Sjoerg   // explosion for destructors that can result and the compile time hit.
22517330f729Sjoerg   AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
22527330f729Sjoerg   AC.getCFGBuildOptions().AddEHEdges = false;
22537330f729Sjoerg   AC.getCFGBuildOptions().AddInitializers = true;
22547330f729Sjoerg   AC.getCFGBuildOptions().AddImplicitDtors = true;
22557330f729Sjoerg   AC.getCFGBuildOptions().AddTemporaryDtors = true;
22567330f729Sjoerg   AC.getCFGBuildOptions().AddCXXNewAllocator = false;
22577330f729Sjoerg   AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
22587330f729Sjoerg 
22597330f729Sjoerg   // Force that certain expressions appear as CFGElements in the CFG.  This
22607330f729Sjoerg   // is used to speed up various analyses.
22617330f729Sjoerg   // FIXME: This isn't the right factoring.  This is here for initial
22627330f729Sjoerg   // prototyping, but we need a way for analyses to say what expressions they
22637330f729Sjoerg   // expect to always be CFGElements and then fill in the BuildOptions
22647330f729Sjoerg   // appropriately.  This is essentially a layering violation.
22657330f729Sjoerg   if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
22667330f729Sjoerg       P.enableConsumedAnalysis) {
22677330f729Sjoerg     // Unreachable code analysis and thread safety require a linearized CFG.
22687330f729Sjoerg     AC.getCFGBuildOptions().setAllAlwaysAdd();
22697330f729Sjoerg   }
22707330f729Sjoerg   else {
22717330f729Sjoerg     AC.getCFGBuildOptions()
22727330f729Sjoerg       .setAlwaysAdd(Stmt::BinaryOperatorClass)
22737330f729Sjoerg       .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
22747330f729Sjoerg       .setAlwaysAdd(Stmt::BlockExprClass)
22757330f729Sjoerg       .setAlwaysAdd(Stmt::CStyleCastExprClass)
22767330f729Sjoerg       .setAlwaysAdd(Stmt::DeclRefExprClass)
22777330f729Sjoerg       .setAlwaysAdd(Stmt::ImplicitCastExprClass)
22787330f729Sjoerg       .setAlwaysAdd(Stmt::UnaryOperatorClass)
22797330f729Sjoerg       .setAlwaysAdd(Stmt::AttributedStmtClass);
22807330f729Sjoerg   }
22817330f729Sjoerg 
22827330f729Sjoerg   // Install the logical handler.
22837330f729Sjoerg   llvm::Optional<LogicalErrorHandler> LEH;
22847330f729Sjoerg   if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) {
22857330f729Sjoerg     LEH.emplace(S);
22867330f729Sjoerg     AC.getCFGBuildOptions().Observer = &*LEH;
22877330f729Sjoerg   }
22887330f729Sjoerg 
22897330f729Sjoerg   // Emit delayed diagnostics.
22907330f729Sjoerg   if (!fscope->PossiblyUnreachableDiags.empty()) {
22917330f729Sjoerg     bool analyzed = false;
22927330f729Sjoerg 
22937330f729Sjoerg     // Register the expressions with the CFGBuilder.
22947330f729Sjoerg     for (const auto &D : fscope->PossiblyUnreachableDiags) {
22957330f729Sjoerg       for (const Stmt *S : D.Stmts)
22967330f729Sjoerg         AC.registerForcedBlockExpression(S);
22977330f729Sjoerg     }
22987330f729Sjoerg 
22997330f729Sjoerg     if (AC.getCFG()) {
23007330f729Sjoerg       analyzed = true;
23017330f729Sjoerg       for (const auto &D : fscope->PossiblyUnreachableDiags) {
23027330f729Sjoerg         bool AllReachable = true;
23037330f729Sjoerg         for (const Stmt *S : D.Stmts) {
23047330f729Sjoerg           const CFGBlock *block = AC.getBlockForRegisteredExpression(S);
23057330f729Sjoerg           CFGReverseBlockReachabilityAnalysis *cra =
23067330f729Sjoerg               AC.getCFGReachablityAnalysis();
23077330f729Sjoerg           // FIXME: We should be able to assert that block is non-null, but
23087330f729Sjoerg           // the CFG analysis can skip potentially-evaluated expressions in
23097330f729Sjoerg           // edge cases; see test/Sema/vla-2.c.
23107330f729Sjoerg           if (block && cra) {
23117330f729Sjoerg             // Can this block be reached from the entrance?
23127330f729Sjoerg             if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) {
23137330f729Sjoerg               AllReachable = false;
23147330f729Sjoerg               break;
23157330f729Sjoerg             }
23167330f729Sjoerg           }
23177330f729Sjoerg           // If we cannot map to a basic block, assume the statement is
23187330f729Sjoerg           // reachable.
23197330f729Sjoerg         }
23207330f729Sjoerg 
23217330f729Sjoerg         if (AllReachable)
23227330f729Sjoerg           S.Diag(D.Loc, D.PD);
23237330f729Sjoerg       }
23247330f729Sjoerg     }
23257330f729Sjoerg 
23267330f729Sjoerg     if (!analyzed)
23277330f729Sjoerg       flushDiagnostics(S, fscope);
23287330f729Sjoerg   }
23297330f729Sjoerg 
23307330f729Sjoerg   // Warning: check missing 'return'
23317330f729Sjoerg   if (P.enableCheckFallThrough) {
23327330f729Sjoerg     const CheckFallThroughDiagnostics &CD =
23337330f729Sjoerg         (isa<BlockDecl>(D)
23347330f729Sjoerg              ? CheckFallThroughDiagnostics::MakeForBlock()
23357330f729Sjoerg              : (isa<CXXMethodDecl>(D) &&
23367330f729Sjoerg                 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
23377330f729Sjoerg                 cast<CXXMethodDecl>(D)->getParent()->isLambda())
23387330f729Sjoerg                    ? CheckFallThroughDiagnostics::MakeForLambda()
23397330f729Sjoerg                    : (fscope->isCoroutine()
23407330f729Sjoerg                           ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
23417330f729Sjoerg                           : CheckFallThroughDiagnostics::MakeForFunction(D)));
23427330f729Sjoerg     CheckFallThroughForBody(S, D, Body, BlockType, CD, AC, fscope);
23437330f729Sjoerg   }
23447330f729Sjoerg 
23457330f729Sjoerg   // Warning: check for unreachable code
23467330f729Sjoerg   if (P.enableCheckUnreachable) {
23477330f729Sjoerg     // Only check for unreachable code on non-template instantiations.
23487330f729Sjoerg     // Different template instantiations can effectively change the control-flow
23497330f729Sjoerg     // and it is very difficult to prove that a snippet of code in a template
23507330f729Sjoerg     // is unreachable for all instantiations.
23517330f729Sjoerg     bool isTemplateInstantiation = false;
23527330f729Sjoerg     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
23537330f729Sjoerg       isTemplateInstantiation = Function->isTemplateInstantiation();
23547330f729Sjoerg     if (!isTemplateInstantiation)
23557330f729Sjoerg       CheckUnreachable(S, AC);
23567330f729Sjoerg   }
23577330f729Sjoerg 
23587330f729Sjoerg   // Check for thread safety violations
23597330f729Sjoerg   if (P.enableThreadSafetyAnalysis) {
23607330f729Sjoerg     SourceLocation FL = AC.getDecl()->getLocation();
23617330f729Sjoerg     SourceLocation FEL = AC.getDecl()->getEndLoc();
23627330f729Sjoerg     threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
23637330f729Sjoerg     if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
23647330f729Sjoerg       Reporter.setIssueBetaWarnings(true);
23657330f729Sjoerg     if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
23667330f729Sjoerg       Reporter.setVerbose(true);
23677330f729Sjoerg 
23687330f729Sjoerg     threadSafety::runThreadSafetyAnalysis(AC, Reporter,
23697330f729Sjoerg                                           &S.ThreadSafetyDeclCache);
23707330f729Sjoerg     Reporter.emitDiagnostics();
23717330f729Sjoerg   }
23727330f729Sjoerg 
23737330f729Sjoerg   // Check for violations of consumed properties.
23747330f729Sjoerg   if (P.enableConsumedAnalysis) {
23757330f729Sjoerg     consumed::ConsumedWarningsHandler WarningHandler(S);
23767330f729Sjoerg     consumed::ConsumedAnalyzer Analyzer(WarningHandler);
23777330f729Sjoerg     Analyzer.run(AC);
23787330f729Sjoerg   }
23797330f729Sjoerg 
23807330f729Sjoerg   if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
23817330f729Sjoerg       !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
2382*e038c9c4Sjoerg       !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc()) ||
2383*e038c9c4Sjoerg       !Diags.isIgnored(diag::warn_uninit_const_reference, D->getBeginLoc())) {
23847330f729Sjoerg     if (CFG *cfg = AC.getCFG()) {
23857330f729Sjoerg       UninitValsDiagReporter reporter(S);
23867330f729Sjoerg       UninitVariablesAnalysisStats stats;
23877330f729Sjoerg       std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
23887330f729Sjoerg       runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
23897330f729Sjoerg                                         reporter, stats);
23907330f729Sjoerg 
23917330f729Sjoerg       if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
23927330f729Sjoerg         ++NumUninitAnalysisFunctions;
23937330f729Sjoerg         NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
23947330f729Sjoerg         NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
23957330f729Sjoerg         MaxUninitAnalysisVariablesPerFunction =
23967330f729Sjoerg             std::max(MaxUninitAnalysisVariablesPerFunction,
23977330f729Sjoerg                      stats.NumVariablesAnalyzed);
23987330f729Sjoerg         MaxUninitAnalysisBlockVisitsPerFunction =
23997330f729Sjoerg             std::max(MaxUninitAnalysisBlockVisitsPerFunction,
24007330f729Sjoerg                      stats.NumBlockVisits);
24017330f729Sjoerg       }
24027330f729Sjoerg     }
24037330f729Sjoerg   }
24047330f729Sjoerg 
2405*e038c9c4Sjoerg   // Check for violations of "called once" parameter properties.
2406*e038c9c4Sjoerg   if (S.getLangOpts().ObjC && !S.getLangOpts().CPlusPlus &&
2407*e038c9c4Sjoerg       shouldAnalyzeCalledOnceParameters(Diags, D->getBeginLoc())) {
2408*e038c9c4Sjoerg     if (AC.getCFG()) {
2409*e038c9c4Sjoerg       CalledOnceCheckReporter Reporter(S, IPData->CalledOnceData);
2410*e038c9c4Sjoerg       checkCalledOnceParameters(
2411*e038c9c4Sjoerg           AC, Reporter,
2412*e038c9c4Sjoerg           shouldAnalyzeCalledOnceConventions(Diags, D->getBeginLoc()));
2413*e038c9c4Sjoerg     }
2414*e038c9c4Sjoerg   }
2415*e038c9c4Sjoerg 
24167330f729Sjoerg   bool FallThroughDiagFull =
24177330f729Sjoerg       !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
24187330f729Sjoerg   bool FallThroughDiagPerFunction = !Diags.isIgnored(
24197330f729Sjoerg       diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
24207330f729Sjoerg   if (FallThroughDiagFull || FallThroughDiagPerFunction ||
24217330f729Sjoerg       fscope->HasFallthroughStmt) {
24227330f729Sjoerg     DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
24237330f729Sjoerg   }
24247330f729Sjoerg 
24257330f729Sjoerg   if (S.getLangOpts().ObjCWeak &&
24267330f729Sjoerg       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
24277330f729Sjoerg     diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
24287330f729Sjoerg 
24297330f729Sjoerg 
24307330f729Sjoerg   // Check for infinite self-recursion in functions
24317330f729Sjoerg   if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
24327330f729Sjoerg                        D->getBeginLoc())) {
24337330f729Sjoerg     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
24347330f729Sjoerg       checkRecursiveFunction(S, FD, Body, AC);
24357330f729Sjoerg     }
24367330f729Sjoerg   }
24377330f729Sjoerg 
24387330f729Sjoerg   // Check for throw out of non-throwing function.
24397330f729Sjoerg   if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
24407330f729Sjoerg     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
24417330f729Sjoerg       if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
24427330f729Sjoerg         checkThrowInNonThrowingFunc(S, FD, AC);
24437330f729Sjoerg 
24447330f729Sjoerg   // If none of the previous checks caused a CFG build, trigger one here
24457330f729Sjoerg   // for the logical error handler.
24467330f729Sjoerg   if (LogicalErrorHandler::hasActiveDiagnostics(Diags, D->getBeginLoc())) {
24477330f729Sjoerg     AC.getCFG();
24487330f729Sjoerg   }
24497330f729Sjoerg 
24507330f729Sjoerg   // Collect statistics about the CFG if it was built.
24517330f729Sjoerg   if (S.CollectStats && AC.isCFGBuilt()) {
24527330f729Sjoerg     ++NumFunctionsAnalyzed;
24537330f729Sjoerg     if (CFG *cfg = AC.getCFG()) {
24547330f729Sjoerg       // If we successfully built a CFG for this context, record some more
24557330f729Sjoerg       // detail information about it.
24567330f729Sjoerg       NumCFGBlocks += cfg->getNumBlockIDs();
24577330f729Sjoerg       MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
24587330f729Sjoerg                                          cfg->getNumBlockIDs());
24597330f729Sjoerg     } else {
24607330f729Sjoerg       ++NumFunctionsWithBadCFGs;
24617330f729Sjoerg     }
24627330f729Sjoerg   }
24637330f729Sjoerg }
24647330f729Sjoerg 
PrintStats() const24657330f729Sjoerg void clang::sema::AnalysisBasedWarnings::PrintStats() const {
24667330f729Sjoerg   llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
24677330f729Sjoerg 
24687330f729Sjoerg   unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
24697330f729Sjoerg   unsigned AvgCFGBlocksPerFunction =
24707330f729Sjoerg       !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
24717330f729Sjoerg   llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
24727330f729Sjoerg                << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
24737330f729Sjoerg                << "  " << NumCFGBlocks << " CFG blocks built.\n"
24747330f729Sjoerg                << "  " << AvgCFGBlocksPerFunction
24757330f729Sjoerg                << " average CFG blocks per function.\n"
24767330f729Sjoerg                << "  " << MaxCFGBlocksPerFunction
24777330f729Sjoerg                << " max CFG blocks per function.\n";
24787330f729Sjoerg 
24797330f729Sjoerg   unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
24807330f729Sjoerg       : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
24817330f729Sjoerg   unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
24827330f729Sjoerg       : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
24837330f729Sjoerg   llvm::errs() << NumUninitAnalysisFunctions
24847330f729Sjoerg                << " functions analyzed for uninitialiazed variables\n"
24857330f729Sjoerg                << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
24867330f729Sjoerg                << "  " << AvgUninitVariablesPerFunction
24877330f729Sjoerg                << " average variables per function.\n"
24887330f729Sjoerg                << "  " << MaxUninitAnalysisVariablesPerFunction
24897330f729Sjoerg                << " max variables per function.\n"
24907330f729Sjoerg                << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
24917330f729Sjoerg                << "  " << AvgUninitBlockVisitsPerFunction
24927330f729Sjoerg                << " average block visits per function.\n"
24937330f729Sjoerg                << "  " << MaxUninitAnalysisBlockVisitsPerFunction
24947330f729Sjoerg                << " max block visits per function.\n";
24957330f729Sjoerg }
2496