xref: /minix3/external/bsd/llvm/dist/clang/lib/Sema/AnalysisBasedWarnings.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1f4a2713aSLionel Sambuc //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file defines analysis_warnings::[Policy,Executor].
11f4a2713aSLionel Sambuc // Together they are used by Sema to issue warnings based on inexpensive
12f4a2713aSLionel Sambuc // static analysis algorithms in libAnalysis.
13f4a2713aSLionel Sambuc //
14f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
15f4a2713aSLionel Sambuc 
16f4a2713aSLionel Sambuc #include "clang/Sema/AnalysisBasedWarnings.h"
17f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
18f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
19f4a2713aSLionel Sambuc #include "clang/AST/EvaluatedExprVisitor.h"
20f4a2713aSLionel Sambuc #include "clang/AST/ExprCXX.h"
21f4a2713aSLionel Sambuc #include "clang/AST/ExprObjC.h"
22f4a2713aSLionel Sambuc #include "clang/AST/ParentMap.h"
23f4a2713aSLionel Sambuc #include "clang/AST/RecursiveASTVisitor.h"
24f4a2713aSLionel Sambuc #include "clang/AST/StmtCXX.h"
25f4a2713aSLionel Sambuc #include "clang/AST/StmtObjC.h"
26f4a2713aSLionel Sambuc #include "clang/AST/StmtVisitor.h"
27f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
28f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/Consumed.h"
29f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/ReachableCode.h"
30f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/ThreadSafety.h"
31f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/UninitializedValues.h"
32f4a2713aSLionel Sambuc #include "clang/Analysis/AnalysisContext.h"
33f4a2713aSLionel Sambuc #include "clang/Analysis/CFG.h"
34f4a2713aSLionel Sambuc #include "clang/Analysis/CFGStmtMap.h"
35f4a2713aSLionel Sambuc #include "clang/Basic/SourceLocation.h"
36f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
37f4a2713aSLionel Sambuc #include "clang/Lex/Lexer.h"
38f4a2713aSLionel Sambuc #include "clang/Lex/Preprocessor.h"
39f4a2713aSLionel Sambuc #include "clang/Sema/ScopeInfo.h"
40f4a2713aSLionel Sambuc #include "clang/Sema/SemaInternal.h"
41f4a2713aSLionel Sambuc #include "llvm/ADT/ArrayRef.h"
42f4a2713aSLionel Sambuc #include "llvm/ADT/BitVector.h"
43f4a2713aSLionel Sambuc #include "llvm/ADT/FoldingSet.h"
44f4a2713aSLionel Sambuc #include "llvm/ADT/ImmutableMap.h"
45f4a2713aSLionel Sambuc #include "llvm/ADT/MapVector.h"
46f4a2713aSLionel Sambuc #include "llvm/ADT/PostOrderIterator.h"
47f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
48f4a2713aSLionel Sambuc #include "llvm/ADT/SmallVector.h"
49f4a2713aSLionel Sambuc #include "llvm/ADT/StringRef.h"
50f4a2713aSLionel Sambuc #include "llvm/Support/Casting.h"
51f4a2713aSLionel Sambuc #include <algorithm>
52f4a2713aSLionel Sambuc #include <deque>
53f4a2713aSLionel Sambuc #include <iterator>
54f4a2713aSLionel Sambuc #include <vector>
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc using namespace clang;
57f4a2713aSLionel Sambuc 
58f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
59f4a2713aSLionel Sambuc // Unreachable code analysis.
60f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
61f4a2713aSLionel Sambuc 
62f4a2713aSLionel Sambuc namespace {
63f4a2713aSLionel Sambuc   class UnreachableCodeHandler : public reachable_code::Callback {
64f4a2713aSLionel Sambuc     Sema &S;
65f4a2713aSLionel Sambuc   public:
UnreachableCodeHandler(Sema & s)66f4a2713aSLionel Sambuc     UnreachableCodeHandler(Sema &s) : S(s) {}
67f4a2713aSLionel Sambuc 
HandleUnreachable(reachable_code::UnreachableKind UK,SourceLocation L,SourceRange SilenceableCondVal,SourceRange R1,SourceRange R2)68*0a6a1f1dSLionel Sambuc     void HandleUnreachable(reachable_code::UnreachableKind UK,
69*0a6a1f1dSLionel Sambuc                            SourceLocation L,
70*0a6a1f1dSLionel Sambuc                            SourceRange SilenceableCondVal,
71*0a6a1f1dSLionel Sambuc                            SourceRange R1,
72*0a6a1f1dSLionel Sambuc                            SourceRange R2) override {
73*0a6a1f1dSLionel Sambuc       unsigned diag = diag::warn_unreachable;
74*0a6a1f1dSLionel Sambuc       switch (UK) {
75*0a6a1f1dSLionel Sambuc         case reachable_code::UK_Break:
76*0a6a1f1dSLionel Sambuc           diag = diag::warn_unreachable_break;
77*0a6a1f1dSLionel Sambuc           break;
78*0a6a1f1dSLionel Sambuc         case reachable_code::UK_Return:
79*0a6a1f1dSLionel Sambuc           diag = diag::warn_unreachable_return;
80*0a6a1f1dSLionel Sambuc           break;
81*0a6a1f1dSLionel Sambuc         case reachable_code::UK_Loop_Increment:
82*0a6a1f1dSLionel Sambuc           diag = diag::warn_unreachable_loop_increment;
83*0a6a1f1dSLionel Sambuc           break;
84*0a6a1f1dSLionel Sambuc         case reachable_code::UK_Other:
85*0a6a1f1dSLionel Sambuc           break;
86*0a6a1f1dSLionel Sambuc       }
87*0a6a1f1dSLionel Sambuc 
88*0a6a1f1dSLionel Sambuc       S.Diag(L, diag) << R1 << R2;
89*0a6a1f1dSLionel Sambuc 
90*0a6a1f1dSLionel Sambuc       SourceLocation Open = SilenceableCondVal.getBegin();
91*0a6a1f1dSLionel Sambuc       if (Open.isValid()) {
92*0a6a1f1dSLionel Sambuc         SourceLocation Close = SilenceableCondVal.getEnd();
93*0a6a1f1dSLionel Sambuc         Close = S.getLocForEndOfToken(Close);
94*0a6a1f1dSLionel Sambuc         if (Close.isValid()) {
95*0a6a1f1dSLionel Sambuc           S.Diag(Open, diag::note_unreachable_silence)
96*0a6a1f1dSLionel Sambuc             << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97*0a6a1f1dSLionel Sambuc             << FixItHint::CreateInsertion(Close, ")");
98*0a6a1f1dSLionel Sambuc         }
99*0a6a1f1dSLionel Sambuc       }
100f4a2713aSLionel Sambuc     }
101f4a2713aSLionel Sambuc   };
102f4a2713aSLionel Sambuc }
103f4a2713aSLionel Sambuc 
104f4a2713aSLionel Sambuc /// CheckUnreachable - Check for unreachable code.
CheckUnreachable(Sema & S,AnalysisDeclContext & AC)105f4a2713aSLionel Sambuc static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
106*0a6a1f1dSLionel Sambuc   // As a heuristic prune all diagnostics not in the main file.  Currently
107*0a6a1f1dSLionel Sambuc   // the majority of warnings in headers are false positives.  These
108*0a6a1f1dSLionel Sambuc   // are largely caused by configuration state, e.g. preprocessor
109*0a6a1f1dSLionel Sambuc   // defined code, etc.
110*0a6a1f1dSLionel Sambuc   //
111*0a6a1f1dSLionel Sambuc   // Note that this is also a performance optimization.  Analyzing
112*0a6a1f1dSLionel Sambuc   // headers many times can be expensive.
113*0a6a1f1dSLionel Sambuc   if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114*0a6a1f1dSLionel Sambuc     return;
115*0a6a1f1dSLionel Sambuc 
116f4a2713aSLionel Sambuc   UnreachableCodeHandler UC(S);
117*0a6a1f1dSLionel Sambuc   reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
118*0a6a1f1dSLionel Sambuc }
119*0a6a1f1dSLionel Sambuc 
120*0a6a1f1dSLionel Sambuc /// \brief Warn on logical operator errors in CFGBuilder
121*0a6a1f1dSLionel Sambuc class LogicalErrorHandler : public CFGCallback {
122*0a6a1f1dSLionel Sambuc   Sema &S;
123*0a6a1f1dSLionel Sambuc 
124*0a6a1f1dSLionel Sambuc public:
LogicalErrorHandler(Sema & S)125*0a6a1f1dSLionel Sambuc   LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
126*0a6a1f1dSLionel Sambuc 
HasMacroID(const Expr * E)127*0a6a1f1dSLionel Sambuc   static bool HasMacroID(const Expr *E) {
128*0a6a1f1dSLionel Sambuc     if (E->getExprLoc().isMacroID())
129*0a6a1f1dSLionel Sambuc       return true;
130*0a6a1f1dSLionel Sambuc 
131*0a6a1f1dSLionel Sambuc     // Recurse to children.
132*0a6a1f1dSLionel Sambuc     for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
133*0a6a1f1dSLionel Sambuc       if (*SubStmts)
134*0a6a1f1dSLionel Sambuc         if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
135*0a6a1f1dSLionel Sambuc           if (HasMacroID(SubExpr))
136*0a6a1f1dSLionel Sambuc             return true;
137*0a6a1f1dSLionel Sambuc 
138*0a6a1f1dSLionel Sambuc     return false;
139*0a6a1f1dSLionel Sambuc   }
140*0a6a1f1dSLionel Sambuc 
compareAlwaysTrue(const BinaryOperator * B,bool isAlwaysTrue)141*0a6a1f1dSLionel Sambuc   void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
142*0a6a1f1dSLionel Sambuc     if (HasMacroID(B))
143*0a6a1f1dSLionel Sambuc       return;
144*0a6a1f1dSLionel Sambuc 
145*0a6a1f1dSLionel Sambuc     SourceRange DiagRange = B->getSourceRange();
146*0a6a1f1dSLionel Sambuc     S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147*0a6a1f1dSLionel Sambuc         << DiagRange << isAlwaysTrue;
148*0a6a1f1dSLionel Sambuc   }
149*0a6a1f1dSLionel Sambuc 
compareBitwiseEquality(const BinaryOperator * B,bool isAlwaysTrue)150*0a6a1f1dSLionel Sambuc   void compareBitwiseEquality(const BinaryOperator *B, bool isAlwaysTrue) {
151*0a6a1f1dSLionel Sambuc     if (HasMacroID(B))
152*0a6a1f1dSLionel Sambuc       return;
153*0a6a1f1dSLionel Sambuc 
154*0a6a1f1dSLionel Sambuc     SourceRange DiagRange = B->getSourceRange();
155*0a6a1f1dSLionel Sambuc     S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
156*0a6a1f1dSLionel Sambuc         << DiagRange << isAlwaysTrue;
157*0a6a1f1dSLionel Sambuc   }
158*0a6a1f1dSLionel Sambuc };
159*0a6a1f1dSLionel Sambuc 
160*0a6a1f1dSLionel Sambuc 
161*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
162*0a6a1f1dSLionel Sambuc // Check for infinite self-recursion in functions
163*0a6a1f1dSLionel Sambuc //===----------------------------------------------------------------------===//
164*0a6a1f1dSLionel Sambuc 
165*0a6a1f1dSLionel Sambuc // All blocks are in one of three states.  States are ordered so that blocks
166*0a6a1f1dSLionel Sambuc // can only move to higher states.
167*0a6a1f1dSLionel Sambuc enum RecursiveState {
168*0a6a1f1dSLionel Sambuc   FoundNoPath,
169*0a6a1f1dSLionel Sambuc   FoundPath,
170*0a6a1f1dSLionel Sambuc   FoundPathWithNoRecursiveCall
171*0a6a1f1dSLionel Sambuc };
172*0a6a1f1dSLionel Sambuc 
checkForFunctionCall(Sema & S,const FunctionDecl * FD,CFGBlock & Block,unsigned ExitID,llvm::SmallVectorImpl<RecursiveState> & States,RecursiveState State)173*0a6a1f1dSLionel Sambuc static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
174*0a6a1f1dSLionel Sambuc                                  CFGBlock &Block, unsigned ExitID,
175*0a6a1f1dSLionel Sambuc                                  llvm::SmallVectorImpl<RecursiveState> &States,
176*0a6a1f1dSLionel Sambuc                                  RecursiveState State) {
177*0a6a1f1dSLionel Sambuc   unsigned ID = Block.getBlockID();
178*0a6a1f1dSLionel Sambuc 
179*0a6a1f1dSLionel Sambuc   // A block's state can only move to a higher state.
180*0a6a1f1dSLionel Sambuc   if (States[ID] >= State)
181*0a6a1f1dSLionel Sambuc     return;
182*0a6a1f1dSLionel Sambuc 
183*0a6a1f1dSLionel Sambuc   States[ID] = State;
184*0a6a1f1dSLionel Sambuc 
185*0a6a1f1dSLionel Sambuc   // Found a path to the exit node without a recursive call.
186*0a6a1f1dSLionel Sambuc   if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
187*0a6a1f1dSLionel Sambuc     return;
188*0a6a1f1dSLionel Sambuc 
189*0a6a1f1dSLionel Sambuc   if (State == FoundPathWithNoRecursiveCall) {
190*0a6a1f1dSLionel Sambuc     // If the current state is FoundPathWithNoRecursiveCall, the successors
191*0a6a1f1dSLionel Sambuc     // will be either FoundPathWithNoRecursiveCall or FoundPath.  To determine
192*0a6a1f1dSLionel Sambuc     // which, process all the Stmt's in this block to find any recursive calls.
193*0a6a1f1dSLionel Sambuc     for (const auto &B : Block) {
194*0a6a1f1dSLionel Sambuc       if (B.getKind() != CFGElement::Statement)
195*0a6a1f1dSLionel Sambuc         continue;
196*0a6a1f1dSLionel Sambuc 
197*0a6a1f1dSLionel Sambuc       const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
198*0a6a1f1dSLionel Sambuc       if (CE && CE->getCalleeDecl() &&
199*0a6a1f1dSLionel Sambuc           CE->getCalleeDecl()->getCanonicalDecl() == FD) {
200*0a6a1f1dSLionel Sambuc 
201*0a6a1f1dSLionel Sambuc         // Skip function calls which are qualified with a templated class.
202*0a6a1f1dSLionel Sambuc         if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
203*0a6a1f1dSLionel Sambuc                 CE->getCallee()->IgnoreParenImpCasts())) {
204*0a6a1f1dSLionel Sambuc           if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
205*0a6a1f1dSLionel Sambuc             if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
206*0a6a1f1dSLionel Sambuc                 isa<TemplateSpecializationType>(NNS->getAsType())) {
207*0a6a1f1dSLionel Sambuc                continue;
208*0a6a1f1dSLionel Sambuc             }
209*0a6a1f1dSLionel Sambuc           }
210*0a6a1f1dSLionel Sambuc         }
211*0a6a1f1dSLionel Sambuc 
212*0a6a1f1dSLionel Sambuc         if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
213*0a6a1f1dSLionel Sambuc           if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
214*0a6a1f1dSLionel Sambuc               !MCE->getMethodDecl()->isVirtual()) {
215*0a6a1f1dSLionel Sambuc             State = FoundPath;
216*0a6a1f1dSLionel Sambuc             break;
217*0a6a1f1dSLionel Sambuc           }
218*0a6a1f1dSLionel Sambuc         } else {
219*0a6a1f1dSLionel Sambuc           State = FoundPath;
220*0a6a1f1dSLionel Sambuc           break;
221*0a6a1f1dSLionel Sambuc         }
222*0a6a1f1dSLionel Sambuc       }
223*0a6a1f1dSLionel Sambuc     }
224*0a6a1f1dSLionel Sambuc   }
225*0a6a1f1dSLionel Sambuc 
226*0a6a1f1dSLionel Sambuc   for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
227*0a6a1f1dSLionel Sambuc        I != E; ++I)
228*0a6a1f1dSLionel Sambuc     if (*I)
229*0a6a1f1dSLionel Sambuc       checkForFunctionCall(S, FD, **I, ExitID, States, State);
230*0a6a1f1dSLionel Sambuc }
231*0a6a1f1dSLionel Sambuc 
checkRecursiveFunction(Sema & S,const FunctionDecl * FD,const Stmt * Body,AnalysisDeclContext & AC)232*0a6a1f1dSLionel Sambuc static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
233*0a6a1f1dSLionel Sambuc                                    const Stmt *Body,
234*0a6a1f1dSLionel Sambuc                                    AnalysisDeclContext &AC) {
235*0a6a1f1dSLionel Sambuc   FD = FD->getCanonicalDecl();
236*0a6a1f1dSLionel Sambuc 
237*0a6a1f1dSLionel Sambuc   // Only run on non-templated functions and non-templated members of
238*0a6a1f1dSLionel Sambuc   // templated classes.
239*0a6a1f1dSLionel Sambuc   if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
240*0a6a1f1dSLionel Sambuc       FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
241*0a6a1f1dSLionel Sambuc     return;
242*0a6a1f1dSLionel Sambuc 
243*0a6a1f1dSLionel Sambuc   CFG *cfg = AC.getCFG();
244*0a6a1f1dSLionel Sambuc   if (!cfg) return;
245*0a6a1f1dSLionel Sambuc 
246*0a6a1f1dSLionel Sambuc   // If the exit block is unreachable, skip processing the function.
247*0a6a1f1dSLionel Sambuc   if (cfg->getExit().pred_empty())
248*0a6a1f1dSLionel Sambuc     return;
249*0a6a1f1dSLionel Sambuc 
250*0a6a1f1dSLionel Sambuc   // Mark all nodes as FoundNoPath, then begin processing the entry block.
251*0a6a1f1dSLionel Sambuc   llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
252*0a6a1f1dSLionel Sambuc                                                FoundNoPath);
253*0a6a1f1dSLionel Sambuc   checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
254*0a6a1f1dSLionel Sambuc                        states, FoundPathWithNoRecursiveCall);
255*0a6a1f1dSLionel Sambuc 
256*0a6a1f1dSLionel Sambuc   // Check that the exit block is reachable.  This prevents triggering the
257*0a6a1f1dSLionel Sambuc   // warning on functions that do not terminate.
258*0a6a1f1dSLionel Sambuc   if (states[cfg->getExit().getBlockID()] == FoundPath)
259*0a6a1f1dSLionel Sambuc     S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
260f4a2713aSLionel Sambuc }
261f4a2713aSLionel Sambuc 
262f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
263f4a2713aSLionel Sambuc // Check for missing return value.
264f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
265f4a2713aSLionel Sambuc 
266f4a2713aSLionel Sambuc enum ControlFlowKind {
267f4a2713aSLionel Sambuc   UnknownFallThrough,
268f4a2713aSLionel Sambuc   NeverFallThrough,
269f4a2713aSLionel Sambuc   MaybeFallThrough,
270f4a2713aSLionel Sambuc   AlwaysFallThrough,
271f4a2713aSLionel Sambuc   NeverFallThroughOrReturn
272f4a2713aSLionel Sambuc };
273f4a2713aSLionel Sambuc 
274f4a2713aSLionel Sambuc /// CheckFallThrough - Check that we don't fall off the end of a
275f4a2713aSLionel Sambuc /// Statement that should return a value.
276f4a2713aSLionel Sambuc ///
277f4a2713aSLionel Sambuc /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
278f4a2713aSLionel Sambuc /// MaybeFallThrough iff we might or might not fall off the end,
279f4a2713aSLionel Sambuc /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
280f4a2713aSLionel Sambuc /// return.  We assume NeverFallThrough iff we never fall off the end of the
281f4a2713aSLionel Sambuc /// statement but we may return.  We assume that functions not marked noreturn
282f4a2713aSLionel Sambuc /// will return.
CheckFallThrough(AnalysisDeclContext & AC)283f4a2713aSLionel Sambuc static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
284f4a2713aSLionel Sambuc   CFG *cfg = AC.getCFG();
285*0a6a1f1dSLionel Sambuc   if (!cfg) return UnknownFallThrough;
286f4a2713aSLionel Sambuc 
287f4a2713aSLionel Sambuc   // The CFG leaves in dead things, and we don't want the dead code paths to
288f4a2713aSLionel Sambuc   // confuse us, so we mark all live things first.
289f4a2713aSLionel Sambuc   llvm::BitVector live(cfg->getNumBlockIDs());
290f4a2713aSLionel Sambuc   unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
291f4a2713aSLionel Sambuc                                                           live);
292f4a2713aSLionel Sambuc 
293f4a2713aSLionel Sambuc   bool AddEHEdges = AC.getAddEHEdges();
294f4a2713aSLionel Sambuc   if (!AddEHEdges && count != cfg->getNumBlockIDs())
295f4a2713aSLionel Sambuc     // When there are things remaining dead, and we didn't add EH edges
296f4a2713aSLionel Sambuc     // from CallExprs to the catch clauses, we have to go back and
297f4a2713aSLionel Sambuc     // mark them as live.
298*0a6a1f1dSLionel Sambuc     for (const auto *B : *cfg) {
299*0a6a1f1dSLionel Sambuc       if (!live[B->getBlockID()]) {
300*0a6a1f1dSLionel Sambuc         if (B->pred_begin() == B->pred_end()) {
301*0a6a1f1dSLionel Sambuc           if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
302f4a2713aSLionel Sambuc             // When not adding EH edges from calls, catch clauses
303f4a2713aSLionel Sambuc             // can otherwise seem dead.  Avoid noting them as dead.
304*0a6a1f1dSLionel Sambuc             count += reachable_code::ScanReachableFromBlock(B, live);
305f4a2713aSLionel Sambuc           continue;
306f4a2713aSLionel Sambuc         }
307f4a2713aSLionel Sambuc       }
308f4a2713aSLionel Sambuc     }
309f4a2713aSLionel Sambuc 
310f4a2713aSLionel Sambuc   // Now we know what is live, we check the live precessors of the exit block
311f4a2713aSLionel Sambuc   // and look for fall through paths, being careful to ignore normal returns,
312f4a2713aSLionel Sambuc   // and exceptional paths.
313f4a2713aSLionel Sambuc   bool HasLiveReturn = false;
314f4a2713aSLionel Sambuc   bool HasFakeEdge = false;
315f4a2713aSLionel Sambuc   bool HasPlainEdge = false;
316f4a2713aSLionel Sambuc   bool HasAbnormalEdge = false;
317f4a2713aSLionel Sambuc 
318f4a2713aSLionel Sambuc   // Ignore default cases that aren't likely to be reachable because all
319f4a2713aSLionel Sambuc   // enums in a switch(X) have explicit case statements.
320f4a2713aSLionel Sambuc   CFGBlock::FilterOptions FO;
321f4a2713aSLionel Sambuc   FO.IgnoreDefaultsWithCoveredEnums = 1;
322f4a2713aSLionel Sambuc 
323f4a2713aSLionel Sambuc   for (CFGBlock::filtered_pred_iterator
324f4a2713aSLionel Sambuc 	 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
325f4a2713aSLionel Sambuc     const CFGBlock& B = **I;
326f4a2713aSLionel Sambuc     if (!live[B.getBlockID()])
327f4a2713aSLionel Sambuc       continue;
328f4a2713aSLionel Sambuc 
329f4a2713aSLionel Sambuc     // Skip blocks which contain an element marked as no-return. They don't
330f4a2713aSLionel Sambuc     // represent actually viable edges into the exit block, so mark them as
331f4a2713aSLionel Sambuc     // abnormal.
332f4a2713aSLionel Sambuc     if (B.hasNoReturnElement()) {
333f4a2713aSLionel Sambuc       HasAbnormalEdge = true;
334f4a2713aSLionel Sambuc       continue;
335f4a2713aSLionel Sambuc     }
336f4a2713aSLionel Sambuc 
337f4a2713aSLionel Sambuc     // Destructors can appear after the 'return' in the CFG.  This is
338f4a2713aSLionel Sambuc     // normal.  We need to look pass the destructors for the return
339f4a2713aSLionel Sambuc     // statement (if it exists).
340f4a2713aSLionel Sambuc     CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
341f4a2713aSLionel Sambuc 
342f4a2713aSLionel Sambuc     for ( ; ri != re ; ++ri)
343f4a2713aSLionel Sambuc       if (ri->getAs<CFGStmt>())
344f4a2713aSLionel Sambuc         break;
345f4a2713aSLionel Sambuc 
346f4a2713aSLionel Sambuc     // No more CFGElements in the block?
347f4a2713aSLionel Sambuc     if (ri == re) {
348f4a2713aSLionel Sambuc       if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
349f4a2713aSLionel Sambuc         HasAbnormalEdge = true;
350f4a2713aSLionel Sambuc         continue;
351f4a2713aSLionel Sambuc       }
352f4a2713aSLionel Sambuc       // A labeled empty statement, or the entry block...
353f4a2713aSLionel Sambuc       HasPlainEdge = true;
354f4a2713aSLionel Sambuc       continue;
355f4a2713aSLionel Sambuc     }
356f4a2713aSLionel Sambuc 
357f4a2713aSLionel Sambuc     CFGStmt CS = ri->castAs<CFGStmt>();
358f4a2713aSLionel Sambuc     const Stmt *S = CS.getStmt();
359f4a2713aSLionel Sambuc     if (isa<ReturnStmt>(S)) {
360f4a2713aSLionel Sambuc       HasLiveReturn = true;
361f4a2713aSLionel Sambuc       continue;
362f4a2713aSLionel Sambuc     }
363f4a2713aSLionel Sambuc     if (isa<ObjCAtThrowStmt>(S)) {
364f4a2713aSLionel Sambuc       HasFakeEdge = true;
365f4a2713aSLionel Sambuc       continue;
366f4a2713aSLionel Sambuc     }
367f4a2713aSLionel Sambuc     if (isa<CXXThrowExpr>(S)) {
368f4a2713aSLionel Sambuc       HasFakeEdge = true;
369f4a2713aSLionel Sambuc       continue;
370f4a2713aSLionel Sambuc     }
371f4a2713aSLionel Sambuc     if (isa<MSAsmStmt>(S)) {
372f4a2713aSLionel Sambuc       // TODO: Verify this is correct.
373f4a2713aSLionel Sambuc       HasFakeEdge = true;
374f4a2713aSLionel Sambuc       HasLiveReturn = true;
375f4a2713aSLionel Sambuc       continue;
376f4a2713aSLionel Sambuc     }
377f4a2713aSLionel Sambuc     if (isa<CXXTryStmt>(S)) {
378f4a2713aSLionel Sambuc       HasAbnormalEdge = true;
379f4a2713aSLionel Sambuc       continue;
380f4a2713aSLionel Sambuc     }
381f4a2713aSLionel Sambuc     if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
382f4a2713aSLionel Sambuc         == B.succ_end()) {
383f4a2713aSLionel Sambuc       HasAbnormalEdge = true;
384f4a2713aSLionel Sambuc       continue;
385f4a2713aSLionel Sambuc     }
386f4a2713aSLionel Sambuc 
387f4a2713aSLionel Sambuc     HasPlainEdge = true;
388f4a2713aSLionel Sambuc   }
389f4a2713aSLionel Sambuc   if (!HasPlainEdge) {
390f4a2713aSLionel Sambuc     if (HasLiveReturn)
391f4a2713aSLionel Sambuc       return NeverFallThrough;
392f4a2713aSLionel Sambuc     return NeverFallThroughOrReturn;
393f4a2713aSLionel Sambuc   }
394f4a2713aSLionel Sambuc   if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
395f4a2713aSLionel Sambuc     return MaybeFallThrough;
396f4a2713aSLionel Sambuc   // This says AlwaysFallThrough for calls to functions that are not marked
397f4a2713aSLionel Sambuc   // noreturn, that don't return.  If people would like this warning to be more
398f4a2713aSLionel Sambuc   // accurate, such functions should be marked as noreturn.
399f4a2713aSLionel Sambuc   return AlwaysFallThrough;
400f4a2713aSLionel Sambuc }
401f4a2713aSLionel Sambuc 
402f4a2713aSLionel Sambuc namespace {
403f4a2713aSLionel Sambuc 
404f4a2713aSLionel Sambuc struct CheckFallThroughDiagnostics {
405f4a2713aSLionel Sambuc   unsigned diag_MaybeFallThrough_HasNoReturn;
406f4a2713aSLionel Sambuc   unsigned diag_MaybeFallThrough_ReturnsNonVoid;
407f4a2713aSLionel Sambuc   unsigned diag_AlwaysFallThrough_HasNoReturn;
408f4a2713aSLionel Sambuc   unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
409f4a2713aSLionel Sambuc   unsigned diag_NeverFallThroughOrReturn;
410f4a2713aSLionel Sambuc   enum { Function, Block, Lambda } funMode;
411f4a2713aSLionel Sambuc   SourceLocation FuncLoc;
412f4a2713aSLionel Sambuc 
MakeForFunction__anon895ab00e0211::CheckFallThroughDiagnostics413f4a2713aSLionel Sambuc   static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
414f4a2713aSLionel Sambuc     CheckFallThroughDiagnostics D;
415f4a2713aSLionel Sambuc     D.FuncLoc = Func->getLocation();
416f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_HasNoReturn =
417f4a2713aSLionel Sambuc       diag::warn_falloff_noreturn_function;
418f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_ReturnsNonVoid =
419f4a2713aSLionel Sambuc       diag::warn_maybe_falloff_nonvoid_function;
420f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_HasNoReturn =
421f4a2713aSLionel Sambuc       diag::warn_falloff_noreturn_function;
422f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_ReturnsNonVoid =
423f4a2713aSLionel Sambuc       diag::warn_falloff_nonvoid_function;
424f4a2713aSLionel Sambuc 
425f4a2713aSLionel Sambuc     // Don't suggest that virtual functions be marked "noreturn", since they
426f4a2713aSLionel Sambuc     // might be overridden by non-noreturn functions.
427f4a2713aSLionel Sambuc     bool isVirtualMethod = false;
428f4a2713aSLionel Sambuc     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
429f4a2713aSLionel Sambuc       isVirtualMethod = Method->isVirtual();
430f4a2713aSLionel Sambuc 
431f4a2713aSLionel Sambuc     // Don't suggest that template instantiations be marked "noreturn"
432f4a2713aSLionel Sambuc     bool isTemplateInstantiation = false;
433f4a2713aSLionel Sambuc     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
434f4a2713aSLionel Sambuc       isTemplateInstantiation = Function->isTemplateInstantiation();
435f4a2713aSLionel Sambuc 
436f4a2713aSLionel Sambuc     if (!isVirtualMethod && !isTemplateInstantiation)
437f4a2713aSLionel Sambuc       D.diag_NeverFallThroughOrReturn =
438f4a2713aSLionel Sambuc         diag::warn_suggest_noreturn_function;
439f4a2713aSLionel Sambuc     else
440f4a2713aSLionel Sambuc       D.diag_NeverFallThroughOrReturn = 0;
441f4a2713aSLionel Sambuc 
442f4a2713aSLionel Sambuc     D.funMode = Function;
443f4a2713aSLionel Sambuc     return D;
444f4a2713aSLionel Sambuc   }
445f4a2713aSLionel Sambuc 
MakeForBlock__anon895ab00e0211::CheckFallThroughDiagnostics446f4a2713aSLionel Sambuc   static CheckFallThroughDiagnostics MakeForBlock() {
447f4a2713aSLionel Sambuc     CheckFallThroughDiagnostics D;
448f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_HasNoReturn =
449f4a2713aSLionel Sambuc       diag::err_noreturn_block_has_return_expr;
450f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_ReturnsNonVoid =
451f4a2713aSLionel Sambuc       diag::err_maybe_falloff_nonvoid_block;
452f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_HasNoReturn =
453f4a2713aSLionel Sambuc       diag::err_noreturn_block_has_return_expr;
454f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_ReturnsNonVoid =
455f4a2713aSLionel Sambuc       diag::err_falloff_nonvoid_block;
456*0a6a1f1dSLionel Sambuc     D.diag_NeverFallThroughOrReturn = 0;
457f4a2713aSLionel Sambuc     D.funMode = Block;
458f4a2713aSLionel Sambuc     return D;
459f4a2713aSLionel Sambuc   }
460f4a2713aSLionel Sambuc 
MakeForLambda__anon895ab00e0211::CheckFallThroughDiagnostics461f4a2713aSLionel Sambuc   static CheckFallThroughDiagnostics MakeForLambda() {
462f4a2713aSLionel Sambuc     CheckFallThroughDiagnostics D;
463f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_HasNoReturn =
464f4a2713aSLionel Sambuc       diag::err_noreturn_lambda_has_return_expr;
465f4a2713aSLionel Sambuc     D.diag_MaybeFallThrough_ReturnsNonVoid =
466f4a2713aSLionel Sambuc       diag::warn_maybe_falloff_nonvoid_lambda;
467f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_HasNoReturn =
468f4a2713aSLionel Sambuc       diag::err_noreturn_lambda_has_return_expr;
469f4a2713aSLionel Sambuc     D.diag_AlwaysFallThrough_ReturnsNonVoid =
470f4a2713aSLionel Sambuc       diag::warn_falloff_nonvoid_lambda;
471f4a2713aSLionel Sambuc     D.diag_NeverFallThroughOrReturn = 0;
472f4a2713aSLionel Sambuc     D.funMode = Lambda;
473f4a2713aSLionel Sambuc     return D;
474f4a2713aSLionel Sambuc   }
475f4a2713aSLionel Sambuc 
checkDiagnostics__anon895ab00e0211::CheckFallThroughDiagnostics476f4a2713aSLionel Sambuc   bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
477f4a2713aSLionel Sambuc                         bool HasNoReturn) const {
478f4a2713aSLionel Sambuc     if (funMode == Function) {
479f4a2713aSLionel Sambuc       return (ReturnsVoid ||
480*0a6a1f1dSLionel Sambuc               D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
481*0a6a1f1dSLionel Sambuc                           FuncLoc)) &&
482*0a6a1f1dSLionel Sambuc              (!HasNoReturn ||
483*0a6a1f1dSLionel Sambuc               D.isIgnored(diag::warn_noreturn_function_has_return_expr,
484*0a6a1f1dSLionel Sambuc                           FuncLoc)) &&
485*0a6a1f1dSLionel Sambuc              (!ReturnsVoid ||
486*0a6a1f1dSLionel Sambuc               D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
487f4a2713aSLionel Sambuc     }
488f4a2713aSLionel Sambuc 
489f4a2713aSLionel Sambuc     // For blocks / lambdas.
490*0a6a1f1dSLionel Sambuc     return ReturnsVoid && !HasNoReturn;
491f4a2713aSLionel Sambuc   }
492f4a2713aSLionel Sambuc };
493f4a2713aSLionel Sambuc 
494f4a2713aSLionel Sambuc }
495f4a2713aSLionel Sambuc 
496f4a2713aSLionel Sambuc /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
497f4a2713aSLionel Sambuc /// function that should return a value.  Check that we don't fall off the end
498f4a2713aSLionel Sambuc /// of a noreturn function.  We assume that functions and blocks not marked
499f4a2713aSLionel Sambuc /// noreturn will return.
CheckFallThroughForBody(Sema & S,const Decl * D,const Stmt * Body,const BlockExpr * blkExpr,const CheckFallThroughDiagnostics & CD,AnalysisDeclContext & AC)500f4a2713aSLionel Sambuc static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
501f4a2713aSLionel Sambuc                                     const BlockExpr *blkExpr,
502f4a2713aSLionel Sambuc                                     const CheckFallThroughDiagnostics& CD,
503f4a2713aSLionel Sambuc                                     AnalysisDeclContext &AC) {
504f4a2713aSLionel Sambuc 
505f4a2713aSLionel Sambuc   bool ReturnsVoid = false;
506f4a2713aSLionel Sambuc   bool HasNoReturn = false;
507f4a2713aSLionel Sambuc 
508f4a2713aSLionel Sambuc   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
509*0a6a1f1dSLionel Sambuc     ReturnsVoid = FD->getReturnType()->isVoidType();
510f4a2713aSLionel Sambuc     HasNoReturn = FD->isNoReturn();
511f4a2713aSLionel Sambuc   }
512f4a2713aSLionel Sambuc   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
513*0a6a1f1dSLionel Sambuc     ReturnsVoid = MD->getReturnType()->isVoidType();
514f4a2713aSLionel Sambuc     HasNoReturn = MD->hasAttr<NoReturnAttr>();
515f4a2713aSLionel Sambuc   }
516f4a2713aSLionel Sambuc   else if (isa<BlockDecl>(D)) {
517f4a2713aSLionel Sambuc     QualType BlockTy = blkExpr->getType();
518f4a2713aSLionel Sambuc     if (const FunctionType *FT =
519f4a2713aSLionel Sambuc           BlockTy->getPointeeType()->getAs<FunctionType>()) {
520*0a6a1f1dSLionel Sambuc       if (FT->getReturnType()->isVoidType())
521f4a2713aSLionel Sambuc         ReturnsVoid = true;
522f4a2713aSLionel Sambuc       if (FT->getNoReturnAttr())
523f4a2713aSLionel Sambuc         HasNoReturn = true;
524f4a2713aSLionel Sambuc     }
525f4a2713aSLionel Sambuc   }
526f4a2713aSLionel Sambuc 
527f4a2713aSLionel Sambuc   DiagnosticsEngine &Diags = S.getDiagnostics();
528f4a2713aSLionel Sambuc 
529f4a2713aSLionel Sambuc   // Short circuit for compilation speed.
530f4a2713aSLionel Sambuc   if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
531f4a2713aSLionel Sambuc       return;
532f4a2713aSLionel Sambuc 
533*0a6a1f1dSLionel Sambuc   SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
534*0a6a1f1dSLionel Sambuc   // Either in a function body compound statement, or a function-try-block.
535f4a2713aSLionel Sambuc   switch (CheckFallThrough(AC)) {
536f4a2713aSLionel Sambuc     case UnknownFallThrough:
537f4a2713aSLionel Sambuc       break;
538f4a2713aSLionel Sambuc 
539f4a2713aSLionel Sambuc     case MaybeFallThrough:
540f4a2713aSLionel Sambuc       if (HasNoReturn)
541*0a6a1f1dSLionel Sambuc         S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
542f4a2713aSLionel Sambuc       else if (!ReturnsVoid)
543*0a6a1f1dSLionel Sambuc         S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
544f4a2713aSLionel Sambuc       break;
545f4a2713aSLionel Sambuc     case AlwaysFallThrough:
546f4a2713aSLionel Sambuc       if (HasNoReturn)
547*0a6a1f1dSLionel Sambuc         S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
548f4a2713aSLionel Sambuc       else if (!ReturnsVoid)
549*0a6a1f1dSLionel Sambuc         S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
550f4a2713aSLionel Sambuc       break;
551f4a2713aSLionel Sambuc     case NeverFallThroughOrReturn:
552f4a2713aSLionel Sambuc       if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
553f4a2713aSLionel Sambuc         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
554*0a6a1f1dSLionel Sambuc           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
555f4a2713aSLionel Sambuc         } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
556*0a6a1f1dSLionel Sambuc           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
557f4a2713aSLionel Sambuc         } else {
558*0a6a1f1dSLionel Sambuc           S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
559f4a2713aSLionel Sambuc         }
560f4a2713aSLionel Sambuc       }
561f4a2713aSLionel Sambuc       break;
562f4a2713aSLionel Sambuc     case NeverFallThrough:
563f4a2713aSLionel Sambuc       break;
564f4a2713aSLionel Sambuc   }
565f4a2713aSLionel Sambuc }
566f4a2713aSLionel Sambuc 
567f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
568f4a2713aSLionel Sambuc // -Wuninitialized
569f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
570f4a2713aSLionel Sambuc 
571f4a2713aSLionel Sambuc namespace {
572f4a2713aSLionel Sambuc /// ContainsReference - A visitor class to search for references to
573f4a2713aSLionel Sambuc /// a particular declaration (the needle) within any evaluated component of an
574f4a2713aSLionel Sambuc /// expression (recursively).
575f4a2713aSLionel Sambuc class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
576f4a2713aSLionel Sambuc   bool FoundReference;
577f4a2713aSLionel Sambuc   const DeclRefExpr *Needle;
578f4a2713aSLionel Sambuc 
579f4a2713aSLionel Sambuc public:
ContainsReference(ASTContext & Context,const DeclRefExpr * Needle)580f4a2713aSLionel Sambuc   ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
581f4a2713aSLionel Sambuc     : EvaluatedExprVisitor<ContainsReference>(Context),
582f4a2713aSLionel Sambuc       FoundReference(false), Needle(Needle) {}
583f4a2713aSLionel Sambuc 
VisitExpr(Expr * E)584f4a2713aSLionel Sambuc   void VisitExpr(Expr *E) {
585f4a2713aSLionel Sambuc     // Stop evaluating if we already have a reference.
586f4a2713aSLionel Sambuc     if (FoundReference)
587f4a2713aSLionel Sambuc       return;
588f4a2713aSLionel Sambuc 
589f4a2713aSLionel Sambuc     EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
590f4a2713aSLionel Sambuc   }
591f4a2713aSLionel Sambuc 
VisitDeclRefExpr(DeclRefExpr * E)592f4a2713aSLionel Sambuc   void VisitDeclRefExpr(DeclRefExpr *E) {
593f4a2713aSLionel Sambuc     if (E == Needle)
594f4a2713aSLionel Sambuc       FoundReference = true;
595f4a2713aSLionel Sambuc     else
596f4a2713aSLionel Sambuc       EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
597f4a2713aSLionel Sambuc   }
598f4a2713aSLionel Sambuc 
doesContainReference() const599f4a2713aSLionel Sambuc   bool doesContainReference() const { return FoundReference; }
600f4a2713aSLionel Sambuc };
601f4a2713aSLionel Sambuc }
602f4a2713aSLionel Sambuc 
SuggestInitializationFixit(Sema & S,const VarDecl * VD)603f4a2713aSLionel Sambuc static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
604f4a2713aSLionel Sambuc   QualType VariableTy = VD->getType().getCanonicalType();
605f4a2713aSLionel Sambuc   if (VariableTy->isBlockPointerType() &&
606f4a2713aSLionel Sambuc       !VD->hasAttr<BlocksAttr>()) {
607*0a6a1f1dSLionel Sambuc     S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
608*0a6a1f1dSLionel Sambuc         << VD->getDeclName()
609f4a2713aSLionel Sambuc         << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
610f4a2713aSLionel Sambuc     return true;
611f4a2713aSLionel Sambuc   }
612f4a2713aSLionel Sambuc 
613f4a2713aSLionel Sambuc   // Don't issue a fixit if there is already an initializer.
614f4a2713aSLionel Sambuc   if (VD->getInit())
615f4a2713aSLionel Sambuc     return false;
616f4a2713aSLionel Sambuc 
617f4a2713aSLionel Sambuc   // Don't suggest a fixit inside macros.
618f4a2713aSLionel Sambuc   if (VD->getLocEnd().isMacroID())
619f4a2713aSLionel Sambuc     return false;
620f4a2713aSLionel Sambuc 
621*0a6a1f1dSLionel Sambuc   SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
622f4a2713aSLionel Sambuc 
623f4a2713aSLionel Sambuc   // Suggest possible initialization (if any).
624f4a2713aSLionel Sambuc   std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
625f4a2713aSLionel Sambuc   if (Init.empty())
626f4a2713aSLionel Sambuc     return false;
627f4a2713aSLionel Sambuc 
628f4a2713aSLionel Sambuc   S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
629f4a2713aSLionel Sambuc     << FixItHint::CreateInsertion(Loc, Init);
630f4a2713aSLionel Sambuc   return true;
631f4a2713aSLionel Sambuc }
632f4a2713aSLionel Sambuc 
633f4a2713aSLionel Sambuc /// Create a fixit to remove an if-like statement, on the assumption that its
634f4a2713aSLionel Sambuc /// condition is CondVal.
CreateIfFixit(Sema & S,const Stmt * If,const Stmt * Then,const Stmt * Else,bool CondVal,FixItHint & Fixit1,FixItHint & Fixit2)635f4a2713aSLionel Sambuc static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
636f4a2713aSLionel Sambuc                           const Stmt *Else, bool CondVal,
637f4a2713aSLionel Sambuc                           FixItHint &Fixit1, FixItHint &Fixit2) {
638f4a2713aSLionel Sambuc   if (CondVal) {
639f4a2713aSLionel Sambuc     // If condition is always true, remove all but the 'then'.
640f4a2713aSLionel Sambuc     Fixit1 = FixItHint::CreateRemoval(
641f4a2713aSLionel Sambuc         CharSourceRange::getCharRange(If->getLocStart(),
642f4a2713aSLionel Sambuc                                       Then->getLocStart()));
643f4a2713aSLionel Sambuc     if (Else) {
644f4a2713aSLionel Sambuc       SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
645f4a2713aSLionel Sambuc           Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
646f4a2713aSLionel Sambuc       Fixit2 = FixItHint::CreateRemoval(
647f4a2713aSLionel Sambuc           SourceRange(ElseKwLoc, Else->getLocEnd()));
648f4a2713aSLionel Sambuc     }
649f4a2713aSLionel Sambuc   } else {
650f4a2713aSLionel Sambuc     // If condition is always false, remove all but the 'else'.
651f4a2713aSLionel Sambuc     if (Else)
652f4a2713aSLionel Sambuc       Fixit1 = FixItHint::CreateRemoval(
653f4a2713aSLionel Sambuc           CharSourceRange::getCharRange(If->getLocStart(),
654f4a2713aSLionel Sambuc                                         Else->getLocStart()));
655f4a2713aSLionel Sambuc     else
656f4a2713aSLionel Sambuc       Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
657f4a2713aSLionel Sambuc   }
658f4a2713aSLionel Sambuc }
659f4a2713aSLionel Sambuc 
660f4a2713aSLionel Sambuc /// DiagUninitUse -- Helper function to produce a diagnostic for an
661f4a2713aSLionel Sambuc /// uninitialized use of a variable.
DiagUninitUse(Sema & S,const VarDecl * VD,const UninitUse & Use,bool IsCapturedByBlock)662f4a2713aSLionel Sambuc static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
663f4a2713aSLionel Sambuc                           bool IsCapturedByBlock) {
664f4a2713aSLionel Sambuc   bool Diagnosed = false;
665f4a2713aSLionel Sambuc 
666f4a2713aSLionel Sambuc   switch (Use.getKind()) {
667f4a2713aSLionel Sambuc   case UninitUse::Always:
668f4a2713aSLionel Sambuc     S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
669f4a2713aSLionel Sambuc         << VD->getDeclName() << IsCapturedByBlock
670f4a2713aSLionel Sambuc         << Use.getUser()->getSourceRange();
671f4a2713aSLionel Sambuc     return;
672f4a2713aSLionel Sambuc 
673f4a2713aSLionel Sambuc   case UninitUse::AfterDecl:
674f4a2713aSLionel Sambuc   case UninitUse::AfterCall:
675f4a2713aSLionel Sambuc     S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
676f4a2713aSLionel Sambuc       << VD->getDeclName() << IsCapturedByBlock
677f4a2713aSLionel Sambuc       << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
678f4a2713aSLionel Sambuc       << const_cast<DeclContext*>(VD->getLexicalDeclContext())
679f4a2713aSLionel Sambuc       << VD->getSourceRange();
680f4a2713aSLionel Sambuc     S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
681f4a2713aSLionel Sambuc       << IsCapturedByBlock << Use.getUser()->getSourceRange();
682f4a2713aSLionel Sambuc     return;
683f4a2713aSLionel Sambuc 
684f4a2713aSLionel Sambuc   case UninitUse::Maybe:
685f4a2713aSLionel Sambuc   case UninitUse::Sometimes:
686f4a2713aSLionel Sambuc     // Carry on to report sometimes-uninitialized branches, if possible,
687f4a2713aSLionel Sambuc     // or a 'may be used uninitialized' diagnostic otherwise.
688f4a2713aSLionel Sambuc     break;
689f4a2713aSLionel Sambuc   }
690f4a2713aSLionel Sambuc 
691f4a2713aSLionel Sambuc   // Diagnose each branch which leads to a sometimes-uninitialized use.
692f4a2713aSLionel Sambuc   for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
693f4a2713aSLionel Sambuc        I != E; ++I) {
694f4a2713aSLionel Sambuc     assert(Use.getKind() == UninitUse::Sometimes);
695f4a2713aSLionel Sambuc 
696f4a2713aSLionel Sambuc     const Expr *User = Use.getUser();
697f4a2713aSLionel Sambuc     const Stmt *Term = I->Terminator;
698f4a2713aSLionel Sambuc 
699f4a2713aSLionel Sambuc     // Information used when building the diagnostic.
700f4a2713aSLionel Sambuc     unsigned DiagKind;
701f4a2713aSLionel Sambuc     StringRef Str;
702f4a2713aSLionel Sambuc     SourceRange Range;
703f4a2713aSLionel Sambuc 
704f4a2713aSLionel Sambuc     // FixIts to suppress the diagnostic by removing the dead condition.
705f4a2713aSLionel Sambuc     // For all binary terminators, branch 0 is taken if the condition is true,
706f4a2713aSLionel Sambuc     // and branch 1 is taken if the condition is false.
707f4a2713aSLionel Sambuc     int RemoveDiagKind = -1;
708f4a2713aSLionel Sambuc     const char *FixitStr =
709f4a2713aSLionel Sambuc         S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
710f4a2713aSLionel Sambuc                                   : (I->Output ? "1" : "0");
711f4a2713aSLionel Sambuc     FixItHint Fixit1, Fixit2;
712f4a2713aSLionel Sambuc 
713f4a2713aSLionel Sambuc     switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
714f4a2713aSLionel Sambuc     default:
715f4a2713aSLionel Sambuc       // Don't know how to report this. Just fall back to 'may be used
716f4a2713aSLionel Sambuc       // uninitialized'. FIXME: Can this happen?
717f4a2713aSLionel Sambuc       continue;
718f4a2713aSLionel Sambuc 
719f4a2713aSLionel Sambuc     // "condition is true / condition is false".
720f4a2713aSLionel Sambuc     case Stmt::IfStmtClass: {
721f4a2713aSLionel Sambuc       const IfStmt *IS = cast<IfStmt>(Term);
722f4a2713aSLionel Sambuc       DiagKind = 0;
723f4a2713aSLionel Sambuc       Str = "if";
724f4a2713aSLionel Sambuc       Range = IS->getCond()->getSourceRange();
725f4a2713aSLionel Sambuc       RemoveDiagKind = 0;
726f4a2713aSLionel Sambuc       CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
727f4a2713aSLionel Sambuc                     I->Output, Fixit1, Fixit2);
728f4a2713aSLionel Sambuc       break;
729f4a2713aSLionel Sambuc     }
730f4a2713aSLionel Sambuc     case Stmt::ConditionalOperatorClass: {
731f4a2713aSLionel Sambuc       const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
732f4a2713aSLionel Sambuc       DiagKind = 0;
733f4a2713aSLionel Sambuc       Str = "?:";
734f4a2713aSLionel Sambuc       Range = CO->getCond()->getSourceRange();
735f4a2713aSLionel Sambuc       RemoveDiagKind = 0;
736f4a2713aSLionel Sambuc       CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
737f4a2713aSLionel Sambuc                     I->Output, Fixit1, Fixit2);
738f4a2713aSLionel Sambuc       break;
739f4a2713aSLionel Sambuc     }
740f4a2713aSLionel Sambuc     case Stmt::BinaryOperatorClass: {
741f4a2713aSLionel Sambuc       const BinaryOperator *BO = cast<BinaryOperator>(Term);
742f4a2713aSLionel Sambuc       if (!BO->isLogicalOp())
743f4a2713aSLionel Sambuc         continue;
744f4a2713aSLionel Sambuc       DiagKind = 0;
745f4a2713aSLionel Sambuc       Str = BO->getOpcodeStr();
746f4a2713aSLionel Sambuc       Range = BO->getLHS()->getSourceRange();
747f4a2713aSLionel Sambuc       RemoveDiagKind = 0;
748f4a2713aSLionel Sambuc       if ((BO->getOpcode() == BO_LAnd && I->Output) ||
749f4a2713aSLionel Sambuc           (BO->getOpcode() == BO_LOr && !I->Output))
750f4a2713aSLionel Sambuc         // true && y -> y, false || y -> y.
751f4a2713aSLionel Sambuc         Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
752f4a2713aSLionel Sambuc                                                       BO->getOperatorLoc()));
753f4a2713aSLionel Sambuc       else
754f4a2713aSLionel Sambuc         // false && y -> false, true || y -> true.
755f4a2713aSLionel Sambuc         Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
756f4a2713aSLionel Sambuc       break;
757f4a2713aSLionel Sambuc     }
758f4a2713aSLionel Sambuc 
759f4a2713aSLionel Sambuc     // "loop is entered / loop is exited".
760f4a2713aSLionel Sambuc     case Stmt::WhileStmtClass:
761f4a2713aSLionel Sambuc       DiagKind = 1;
762f4a2713aSLionel Sambuc       Str = "while";
763f4a2713aSLionel Sambuc       Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
764f4a2713aSLionel Sambuc       RemoveDiagKind = 1;
765f4a2713aSLionel Sambuc       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
766f4a2713aSLionel Sambuc       break;
767f4a2713aSLionel Sambuc     case Stmt::ForStmtClass:
768f4a2713aSLionel Sambuc       DiagKind = 1;
769f4a2713aSLionel Sambuc       Str = "for";
770f4a2713aSLionel Sambuc       Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
771f4a2713aSLionel Sambuc       RemoveDiagKind = 1;
772f4a2713aSLionel Sambuc       if (I->Output)
773f4a2713aSLionel Sambuc         Fixit1 = FixItHint::CreateRemoval(Range);
774f4a2713aSLionel Sambuc       else
775f4a2713aSLionel Sambuc         Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
776f4a2713aSLionel Sambuc       break;
777f4a2713aSLionel Sambuc     case Stmt::CXXForRangeStmtClass:
778f4a2713aSLionel Sambuc       if (I->Output == 1) {
779f4a2713aSLionel Sambuc         // The use occurs if a range-based for loop's body never executes.
780f4a2713aSLionel Sambuc         // That may be impossible, and there's no syntactic fix for this,
781f4a2713aSLionel Sambuc         // so treat it as a 'may be uninitialized' case.
782f4a2713aSLionel Sambuc         continue;
783f4a2713aSLionel Sambuc       }
784f4a2713aSLionel Sambuc       DiagKind = 1;
785f4a2713aSLionel Sambuc       Str = "for";
786f4a2713aSLionel Sambuc       Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
787f4a2713aSLionel Sambuc       break;
788f4a2713aSLionel Sambuc 
789f4a2713aSLionel Sambuc     // "condition is true / loop is exited".
790f4a2713aSLionel Sambuc     case Stmt::DoStmtClass:
791f4a2713aSLionel Sambuc       DiagKind = 2;
792f4a2713aSLionel Sambuc       Str = "do";
793f4a2713aSLionel Sambuc       Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
794f4a2713aSLionel Sambuc       RemoveDiagKind = 1;
795f4a2713aSLionel Sambuc       Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
796f4a2713aSLionel Sambuc       break;
797f4a2713aSLionel Sambuc 
798f4a2713aSLionel Sambuc     // "switch case is taken".
799f4a2713aSLionel Sambuc     case Stmt::CaseStmtClass:
800f4a2713aSLionel Sambuc       DiagKind = 3;
801f4a2713aSLionel Sambuc       Str = "case";
802f4a2713aSLionel Sambuc       Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
803f4a2713aSLionel Sambuc       break;
804f4a2713aSLionel Sambuc     case Stmt::DefaultStmtClass:
805f4a2713aSLionel Sambuc       DiagKind = 3;
806f4a2713aSLionel Sambuc       Str = "default";
807f4a2713aSLionel Sambuc       Range = cast<DefaultStmt>(Term)->getDefaultLoc();
808f4a2713aSLionel Sambuc       break;
809f4a2713aSLionel Sambuc     }
810f4a2713aSLionel Sambuc 
811f4a2713aSLionel Sambuc     S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
812f4a2713aSLionel Sambuc       << VD->getDeclName() << IsCapturedByBlock << DiagKind
813f4a2713aSLionel Sambuc       << Str << I->Output << Range;
814f4a2713aSLionel Sambuc     S.Diag(User->getLocStart(), diag::note_uninit_var_use)
815f4a2713aSLionel Sambuc       << IsCapturedByBlock << User->getSourceRange();
816f4a2713aSLionel Sambuc     if (RemoveDiagKind != -1)
817f4a2713aSLionel Sambuc       S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
818f4a2713aSLionel Sambuc         << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
819f4a2713aSLionel Sambuc 
820f4a2713aSLionel Sambuc     Diagnosed = true;
821f4a2713aSLionel Sambuc   }
822f4a2713aSLionel Sambuc 
823f4a2713aSLionel Sambuc   if (!Diagnosed)
824f4a2713aSLionel Sambuc     S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
825f4a2713aSLionel Sambuc         << VD->getDeclName() << IsCapturedByBlock
826f4a2713aSLionel Sambuc         << Use.getUser()->getSourceRange();
827f4a2713aSLionel Sambuc }
828f4a2713aSLionel Sambuc 
829f4a2713aSLionel Sambuc /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
830f4a2713aSLionel Sambuc /// uninitialized variable. This manages the different forms of diagnostic
831f4a2713aSLionel Sambuc /// emitted for particular types of uses. Returns true if the use was diagnosed
832f4a2713aSLionel Sambuc /// as a warning. If a particular use is one we omit warnings for, returns
833f4a2713aSLionel Sambuc /// false.
DiagnoseUninitializedUse(Sema & S,const VarDecl * VD,const UninitUse & Use,bool alwaysReportSelfInit=false)834f4a2713aSLionel Sambuc static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
835f4a2713aSLionel Sambuc                                      const UninitUse &Use,
836f4a2713aSLionel Sambuc                                      bool alwaysReportSelfInit = false) {
837f4a2713aSLionel Sambuc 
838f4a2713aSLionel Sambuc   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
839f4a2713aSLionel Sambuc     // Inspect the initializer of the variable declaration which is
840f4a2713aSLionel Sambuc     // being referenced prior to its initialization. We emit
841f4a2713aSLionel Sambuc     // specialized diagnostics for self-initialization, and we
842f4a2713aSLionel Sambuc     // specifically avoid warning about self references which take the
843f4a2713aSLionel Sambuc     // form of:
844f4a2713aSLionel Sambuc     //
845f4a2713aSLionel Sambuc     //   int x = x;
846f4a2713aSLionel Sambuc     //
847f4a2713aSLionel Sambuc     // This is used to indicate to GCC that 'x' is intentionally left
848f4a2713aSLionel Sambuc     // uninitialized. Proven code paths which access 'x' in
849f4a2713aSLionel Sambuc     // an uninitialized state after this will still warn.
850f4a2713aSLionel Sambuc     if (const Expr *Initializer = VD->getInit()) {
851f4a2713aSLionel Sambuc       if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
852f4a2713aSLionel Sambuc         return false;
853f4a2713aSLionel Sambuc 
854f4a2713aSLionel Sambuc       ContainsReference CR(S.Context, DRE);
855f4a2713aSLionel Sambuc       CR.Visit(const_cast<Expr*>(Initializer));
856f4a2713aSLionel Sambuc       if (CR.doesContainReference()) {
857f4a2713aSLionel Sambuc         S.Diag(DRE->getLocStart(),
858f4a2713aSLionel Sambuc                diag::warn_uninit_self_reference_in_init)
859f4a2713aSLionel Sambuc           << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
860f4a2713aSLionel Sambuc         return true;
861f4a2713aSLionel Sambuc       }
862f4a2713aSLionel Sambuc     }
863f4a2713aSLionel Sambuc 
864f4a2713aSLionel Sambuc     DiagUninitUse(S, VD, Use, false);
865f4a2713aSLionel Sambuc   } else {
866f4a2713aSLionel Sambuc     const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
867f4a2713aSLionel Sambuc     if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
868f4a2713aSLionel Sambuc       S.Diag(BE->getLocStart(),
869f4a2713aSLionel Sambuc              diag::warn_uninit_byref_blockvar_captured_by_block)
870f4a2713aSLionel Sambuc         << VD->getDeclName();
871f4a2713aSLionel Sambuc     else
872f4a2713aSLionel Sambuc       DiagUninitUse(S, VD, Use, true);
873f4a2713aSLionel Sambuc   }
874f4a2713aSLionel Sambuc 
875f4a2713aSLionel Sambuc   // Report where the variable was declared when the use wasn't within
876f4a2713aSLionel Sambuc   // the initializer of that declaration & we didn't already suggest
877f4a2713aSLionel Sambuc   // an initialization fixit.
878f4a2713aSLionel Sambuc   if (!SuggestInitializationFixit(S, VD))
879f4a2713aSLionel Sambuc     S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
880f4a2713aSLionel Sambuc       << VD->getDeclName();
881f4a2713aSLionel Sambuc 
882f4a2713aSLionel Sambuc   return true;
883f4a2713aSLionel Sambuc }
884f4a2713aSLionel Sambuc 
885f4a2713aSLionel Sambuc namespace {
886f4a2713aSLionel Sambuc   class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
887f4a2713aSLionel Sambuc   public:
FallthroughMapper(Sema & S)888f4a2713aSLionel Sambuc     FallthroughMapper(Sema &S)
889f4a2713aSLionel Sambuc       : FoundSwitchStatements(false),
890f4a2713aSLionel Sambuc         S(S) {
891f4a2713aSLionel Sambuc     }
892f4a2713aSLionel Sambuc 
foundSwitchStatements() const893f4a2713aSLionel Sambuc     bool foundSwitchStatements() const { return FoundSwitchStatements; }
894f4a2713aSLionel Sambuc 
markFallthroughVisited(const AttributedStmt * Stmt)895f4a2713aSLionel Sambuc     void markFallthroughVisited(const AttributedStmt *Stmt) {
896f4a2713aSLionel Sambuc       bool Found = FallthroughStmts.erase(Stmt);
897f4a2713aSLionel Sambuc       assert(Found);
898f4a2713aSLionel Sambuc       (void)Found;
899f4a2713aSLionel Sambuc     }
900f4a2713aSLionel Sambuc 
901f4a2713aSLionel Sambuc     typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
902f4a2713aSLionel Sambuc 
getFallthroughStmts() const903f4a2713aSLionel Sambuc     const AttrStmts &getFallthroughStmts() const {
904f4a2713aSLionel Sambuc       return FallthroughStmts;
905f4a2713aSLionel Sambuc     }
906f4a2713aSLionel Sambuc 
fillReachableBlocks(CFG * Cfg)907f4a2713aSLionel Sambuc     void fillReachableBlocks(CFG *Cfg) {
908f4a2713aSLionel Sambuc       assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
909f4a2713aSLionel Sambuc       std::deque<const CFGBlock *> BlockQueue;
910f4a2713aSLionel Sambuc 
911f4a2713aSLionel Sambuc       ReachableBlocks.insert(&Cfg->getEntry());
912f4a2713aSLionel Sambuc       BlockQueue.push_back(&Cfg->getEntry());
913f4a2713aSLionel Sambuc       // Mark all case blocks reachable to avoid problems with switching on
914f4a2713aSLionel Sambuc       // constants, covered enums, etc.
915f4a2713aSLionel Sambuc       // These blocks can contain fall-through annotations, and we don't want to
916f4a2713aSLionel Sambuc       // issue a warn_fallthrough_attr_unreachable for them.
917*0a6a1f1dSLionel Sambuc       for (const auto *B : *Cfg) {
918f4a2713aSLionel Sambuc         const Stmt *L = B->getLabel();
919*0a6a1f1dSLionel Sambuc         if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
920f4a2713aSLionel Sambuc           BlockQueue.push_back(B);
921f4a2713aSLionel Sambuc       }
922f4a2713aSLionel Sambuc 
923f4a2713aSLionel Sambuc       while (!BlockQueue.empty()) {
924f4a2713aSLionel Sambuc         const CFGBlock *P = BlockQueue.front();
925f4a2713aSLionel Sambuc         BlockQueue.pop_front();
926f4a2713aSLionel Sambuc         for (CFGBlock::const_succ_iterator I = P->succ_begin(),
927f4a2713aSLionel Sambuc                                            E = P->succ_end();
928f4a2713aSLionel Sambuc              I != E; ++I) {
929*0a6a1f1dSLionel Sambuc           if (*I && ReachableBlocks.insert(*I).second)
930f4a2713aSLionel Sambuc             BlockQueue.push_back(*I);
931f4a2713aSLionel Sambuc         }
932f4a2713aSLionel Sambuc       }
933f4a2713aSLionel Sambuc     }
934f4a2713aSLionel Sambuc 
checkFallThroughIntoBlock(const CFGBlock & B,int & AnnotatedCnt)935f4a2713aSLionel Sambuc     bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
936f4a2713aSLionel Sambuc       assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
937f4a2713aSLionel Sambuc 
938f4a2713aSLionel Sambuc       int UnannotatedCnt = 0;
939f4a2713aSLionel Sambuc       AnnotatedCnt = 0;
940f4a2713aSLionel Sambuc 
941*0a6a1f1dSLionel Sambuc       std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
942f4a2713aSLionel Sambuc       while (!BlockQueue.empty()) {
943f4a2713aSLionel Sambuc         const CFGBlock *P = BlockQueue.front();
944f4a2713aSLionel Sambuc         BlockQueue.pop_front();
945*0a6a1f1dSLionel Sambuc         if (!P) continue;
946f4a2713aSLionel Sambuc 
947f4a2713aSLionel Sambuc         const Stmt *Term = P->getTerminator();
948f4a2713aSLionel Sambuc         if (Term && isa<SwitchStmt>(Term))
949f4a2713aSLionel Sambuc           continue; // Switch statement, good.
950f4a2713aSLionel Sambuc 
951f4a2713aSLionel Sambuc         const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
952f4a2713aSLionel Sambuc         if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
953f4a2713aSLionel Sambuc           continue; // Previous case label has no statements, good.
954f4a2713aSLionel Sambuc 
955f4a2713aSLionel Sambuc         const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
956f4a2713aSLionel Sambuc         if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
957f4a2713aSLionel Sambuc           continue; // Case label is preceded with a normal label, good.
958f4a2713aSLionel Sambuc 
959f4a2713aSLionel Sambuc         if (!ReachableBlocks.count(P)) {
960f4a2713aSLionel Sambuc           for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
961f4a2713aSLionel Sambuc                                                 ElemEnd = P->rend();
962f4a2713aSLionel Sambuc                ElemIt != ElemEnd; ++ElemIt) {
963f4a2713aSLionel Sambuc             if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
964f4a2713aSLionel Sambuc               if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
965f4a2713aSLionel Sambuc                 S.Diag(AS->getLocStart(),
966f4a2713aSLionel Sambuc                        diag::warn_fallthrough_attr_unreachable);
967f4a2713aSLionel Sambuc                 markFallthroughVisited(AS);
968f4a2713aSLionel Sambuc                 ++AnnotatedCnt;
969f4a2713aSLionel Sambuc                 break;
970f4a2713aSLionel Sambuc               }
971f4a2713aSLionel Sambuc               // Don't care about other unreachable statements.
972f4a2713aSLionel Sambuc             }
973f4a2713aSLionel Sambuc           }
974f4a2713aSLionel Sambuc           // If there are no unreachable statements, this may be a special
975f4a2713aSLionel Sambuc           // case in CFG:
976f4a2713aSLionel Sambuc           // case X: {
977f4a2713aSLionel Sambuc           //    A a;  // A has a destructor.
978f4a2713aSLionel Sambuc           //    break;
979f4a2713aSLionel Sambuc           // }
980f4a2713aSLionel Sambuc           // // <<<< This place is represented by a 'hanging' CFG block.
981f4a2713aSLionel Sambuc           // case Y:
982f4a2713aSLionel Sambuc           continue;
983f4a2713aSLionel Sambuc         }
984f4a2713aSLionel Sambuc 
985f4a2713aSLionel Sambuc         const Stmt *LastStmt = getLastStmt(*P);
986f4a2713aSLionel Sambuc         if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
987f4a2713aSLionel Sambuc           markFallthroughVisited(AS);
988f4a2713aSLionel Sambuc           ++AnnotatedCnt;
989f4a2713aSLionel Sambuc           continue; // Fallthrough annotation, good.
990f4a2713aSLionel Sambuc         }
991f4a2713aSLionel Sambuc 
992f4a2713aSLionel Sambuc         if (!LastStmt) { // This block contains no executable statements.
993f4a2713aSLionel Sambuc           // Traverse its predecessors.
994f4a2713aSLionel Sambuc           std::copy(P->pred_begin(), P->pred_end(),
995f4a2713aSLionel Sambuc                     std::back_inserter(BlockQueue));
996f4a2713aSLionel Sambuc           continue;
997f4a2713aSLionel Sambuc         }
998f4a2713aSLionel Sambuc 
999f4a2713aSLionel Sambuc         ++UnannotatedCnt;
1000f4a2713aSLionel Sambuc       }
1001f4a2713aSLionel Sambuc       return !!UnannotatedCnt;
1002f4a2713aSLionel Sambuc     }
1003f4a2713aSLionel Sambuc 
1004f4a2713aSLionel Sambuc     // RecursiveASTVisitor setup.
shouldWalkTypesOfTypeLocs() const1005f4a2713aSLionel Sambuc     bool shouldWalkTypesOfTypeLocs() const { return false; }
1006f4a2713aSLionel Sambuc 
VisitAttributedStmt(AttributedStmt * S)1007f4a2713aSLionel Sambuc     bool VisitAttributedStmt(AttributedStmt *S) {
1008f4a2713aSLionel Sambuc       if (asFallThroughAttr(S))
1009f4a2713aSLionel Sambuc         FallthroughStmts.insert(S);
1010f4a2713aSLionel Sambuc       return true;
1011f4a2713aSLionel Sambuc     }
1012f4a2713aSLionel Sambuc 
VisitSwitchStmt(SwitchStmt * S)1013f4a2713aSLionel Sambuc     bool VisitSwitchStmt(SwitchStmt *S) {
1014f4a2713aSLionel Sambuc       FoundSwitchStatements = true;
1015f4a2713aSLionel Sambuc       return true;
1016f4a2713aSLionel Sambuc     }
1017f4a2713aSLionel Sambuc 
1018f4a2713aSLionel Sambuc     // We don't want to traverse local type declarations. We analyze their
1019f4a2713aSLionel Sambuc     // methods separately.
TraverseDecl(Decl * D)1020f4a2713aSLionel Sambuc     bool TraverseDecl(Decl *D) { return true; }
1021f4a2713aSLionel Sambuc 
1022*0a6a1f1dSLionel Sambuc     // We analyze lambda bodies separately. Skip them here.
TraverseLambdaBody(LambdaExpr * LE)1023*0a6a1f1dSLionel Sambuc     bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1024*0a6a1f1dSLionel Sambuc 
1025f4a2713aSLionel Sambuc   private:
1026f4a2713aSLionel Sambuc 
asFallThroughAttr(const Stmt * S)1027f4a2713aSLionel Sambuc     static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1028f4a2713aSLionel Sambuc       if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1029f4a2713aSLionel Sambuc         if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1030f4a2713aSLionel Sambuc           return AS;
1031f4a2713aSLionel Sambuc       }
1032*0a6a1f1dSLionel Sambuc       return nullptr;
1033f4a2713aSLionel Sambuc     }
1034f4a2713aSLionel Sambuc 
getLastStmt(const CFGBlock & B)1035f4a2713aSLionel Sambuc     static const Stmt *getLastStmt(const CFGBlock &B) {
1036f4a2713aSLionel Sambuc       if (const Stmt *Term = B.getTerminator())
1037f4a2713aSLionel Sambuc         return Term;
1038f4a2713aSLionel Sambuc       for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1039f4a2713aSLionel Sambuc                                             ElemEnd = B.rend();
1040f4a2713aSLionel Sambuc                                             ElemIt != ElemEnd; ++ElemIt) {
1041f4a2713aSLionel Sambuc         if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1042f4a2713aSLionel Sambuc           return CS->getStmt();
1043f4a2713aSLionel Sambuc       }
1044f4a2713aSLionel Sambuc       // Workaround to detect a statement thrown out by CFGBuilder:
1045f4a2713aSLionel Sambuc       //   case X: {} case Y:
1046f4a2713aSLionel Sambuc       //   case X: ; case Y:
1047f4a2713aSLionel Sambuc       if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1048f4a2713aSLionel Sambuc         if (!isa<SwitchCase>(SW->getSubStmt()))
1049f4a2713aSLionel Sambuc           return SW->getSubStmt();
1050f4a2713aSLionel Sambuc 
1051*0a6a1f1dSLionel Sambuc       return nullptr;
1052f4a2713aSLionel Sambuc     }
1053f4a2713aSLionel Sambuc 
1054f4a2713aSLionel Sambuc     bool FoundSwitchStatements;
1055f4a2713aSLionel Sambuc     AttrStmts FallthroughStmts;
1056f4a2713aSLionel Sambuc     Sema &S;
1057f4a2713aSLionel Sambuc     llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1058f4a2713aSLionel Sambuc   };
1059f4a2713aSLionel Sambuc }
1060f4a2713aSLionel Sambuc 
DiagnoseSwitchLabelsFallthrough(Sema & S,AnalysisDeclContext & AC,bool PerFunction)1061f4a2713aSLionel Sambuc static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1062f4a2713aSLionel Sambuc                                             bool PerFunction) {
1063f4a2713aSLionel Sambuc   // Only perform this analysis when using C++11.  There is no good workflow
1064f4a2713aSLionel Sambuc   // for this warning when not using C++11.  There is no good way to silence
1065f4a2713aSLionel Sambuc   // the warning (no attribute is available) unless we are using C++11's support
1066f4a2713aSLionel Sambuc   // for generalized attributes.  Once could use pragmas to silence the warning,
1067f4a2713aSLionel Sambuc   // but as a general solution that is gross and not in the spirit of this
1068f4a2713aSLionel Sambuc   // warning.
1069f4a2713aSLionel Sambuc   //
1070f4a2713aSLionel Sambuc   // NOTE: This an intermediate solution.  There are on-going discussions on
1071f4a2713aSLionel Sambuc   // how to properly support this warning outside of C++11 with an annotation.
1072f4a2713aSLionel Sambuc   if (!AC.getASTContext().getLangOpts().CPlusPlus11)
1073f4a2713aSLionel Sambuc     return;
1074f4a2713aSLionel Sambuc 
1075f4a2713aSLionel Sambuc   FallthroughMapper FM(S);
1076f4a2713aSLionel Sambuc   FM.TraverseStmt(AC.getBody());
1077f4a2713aSLionel Sambuc 
1078f4a2713aSLionel Sambuc   if (!FM.foundSwitchStatements())
1079f4a2713aSLionel Sambuc     return;
1080f4a2713aSLionel Sambuc 
1081f4a2713aSLionel Sambuc   if (PerFunction && FM.getFallthroughStmts().empty())
1082f4a2713aSLionel Sambuc     return;
1083f4a2713aSLionel Sambuc 
1084f4a2713aSLionel Sambuc   CFG *Cfg = AC.getCFG();
1085f4a2713aSLionel Sambuc 
1086f4a2713aSLionel Sambuc   if (!Cfg)
1087f4a2713aSLionel Sambuc     return;
1088f4a2713aSLionel Sambuc 
1089f4a2713aSLionel Sambuc   FM.fillReachableBlocks(Cfg);
1090f4a2713aSLionel Sambuc 
1091f4a2713aSLionel Sambuc   for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
1092f4a2713aSLionel Sambuc     const CFGBlock *B = *I;
1093f4a2713aSLionel Sambuc     const Stmt *Label = B->getLabel();
1094f4a2713aSLionel Sambuc 
1095f4a2713aSLionel Sambuc     if (!Label || !isa<SwitchCase>(Label))
1096f4a2713aSLionel Sambuc       continue;
1097f4a2713aSLionel Sambuc 
1098f4a2713aSLionel Sambuc     int AnnotatedCnt;
1099f4a2713aSLionel Sambuc 
1100f4a2713aSLionel Sambuc     if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1101f4a2713aSLionel Sambuc       continue;
1102f4a2713aSLionel Sambuc 
1103f4a2713aSLionel Sambuc     S.Diag(Label->getLocStart(),
1104f4a2713aSLionel Sambuc         PerFunction ? diag::warn_unannotated_fallthrough_per_function
1105f4a2713aSLionel Sambuc                     : diag::warn_unannotated_fallthrough);
1106f4a2713aSLionel Sambuc 
1107f4a2713aSLionel Sambuc     if (!AnnotatedCnt) {
1108f4a2713aSLionel Sambuc       SourceLocation L = Label->getLocStart();
1109f4a2713aSLionel Sambuc       if (L.isMacroID())
1110f4a2713aSLionel Sambuc         continue;
1111f4a2713aSLionel Sambuc       if (S.getLangOpts().CPlusPlus11) {
1112f4a2713aSLionel Sambuc         const Stmt *Term = B->getTerminator();
1113f4a2713aSLionel Sambuc         // Skip empty cases.
1114f4a2713aSLionel Sambuc         while (B->empty() && !Term && B->succ_size() == 1) {
1115f4a2713aSLionel Sambuc           B = *B->succ_begin();
1116f4a2713aSLionel Sambuc           Term = B->getTerminator();
1117f4a2713aSLionel Sambuc         }
1118f4a2713aSLionel Sambuc         if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
1119f4a2713aSLionel Sambuc           Preprocessor &PP = S.getPreprocessor();
1120f4a2713aSLionel Sambuc           TokenValue Tokens[] = {
1121f4a2713aSLionel Sambuc             tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1122f4a2713aSLionel Sambuc             tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1123f4a2713aSLionel Sambuc             tok::r_square, tok::r_square
1124f4a2713aSLionel Sambuc           };
1125f4a2713aSLionel Sambuc           StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1126f4a2713aSLionel Sambuc           StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1127f4a2713aSLionel Sambuc           if (!MacroName.empty())
1128f4a2713aSLionel Sambuc             AnnotationSpelling = MacroName;
1129f4a2713aSLionel Sambuc           SmallString<64> TextToInsert(AnnotationSpelling);
1130f4a2713aSLionel Sambuc           TextToInsert += "; ";
1131f4a2713aSLionel Sambuc           S.Diag(L, diag::note_insert_fallthrough_fixit) <<
1132f4a2713aSLionel Sambuc               AnnotationSpelling <<
1133f4a2713aSLionel Sambuc               FixItHint::CreateInsertion(L, TextToInsert);
1134f4a2713aSLionel Sambuc         }
1135f4a2713aSLionel Sambuc       }
1136f4a2713aSLionel Sambuc       S.Diag(L, diag::note_insert_break_fixit) <<
1137f4a2713aSLionel Sambuc         FixItHint::CreateInsertion(L, "break; ");
1138f4a2713aSLionel Sambuc     }
1139f4a2713aSLionel Sambuc   }
1140f4a2713aSLionel Sambuc 
1141*0a6a1f1dSLionel Sambuc   for (const auto *F : FM.getFallthroughStmts())
1142*0a6a1f1dSLionel Sambuc     S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1143f4a2713aSLionel Sambuc }
1144f4a2713aSLionel Sambuc 
isInLoop(const ASTContext & Ctx,const ParentMap & PM,const Stmt * S)1145f4a2713aSLionel Sambuc static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1146f4a2713aSLionel Sambuc                      const Stmt *S) {
1147f4a2713aSLionel Sambuc   assert(S);
1148f4a2713aSLionel Sambuc 
1149f4a2713aSLionel Sambuc   do {
1150f4a2713aSLionel Sambuc     switch (S->getStmtClass()) {
1151f4a2713aSLionel Sambuc     case Stmt::ForStmtClass:
1152f4a2713aSLionel Sambuc     case Stmt::WhileStmtClass:
1153f4a2713aSLionel Sambuc     case Stmt::CXXForRangeStmtClass:
1154f4a2713aSLionel Sambuc     case Stmt::ObjCForCollectionStmtClass:
1155f4a2713aSLionel Sambuc       return true;
1156f4a2713aSLionel Sambuc     case Stmt::DoStmtClass: {
1157f4a2713aSLionel Sambuc       const Expr *Cond = cast<DoStmt>(S)->getCond();
1158f4a2713aSLionel Sambuc       llvm::APSInt Val;
1159f4a2713aSLionel Sambuc       if (!Cond->EvaluateAsInt(Val, Ctx))
1160f4a2713aSLionel Sambuc         return true;
1161f4a2713aSLionel Sambuc       return Val.getBoolValue();
1162f4a2713aSLionel Sambuc     }
1163f4a2713aSLionel Sambuc     default:
1164f4a2713aSLionel Sambuc       break;
1165f4a2713aSLionel Sambuc     }
1166f4a2713aSLionel Sambuc   } while ((S = PM.getParent(S)));
1167f4a2713aSLionel Sambuc 
1168f4a2713aSLionel Sambuc   return false;
1169f4a2713aSLionel Sambuc }
1170f4a2713aSLionel Sambuc 
1171f4a2713aSLionel Sambuc 
diagnoseRepeatedUseOfWeak(Sema & S,const sema::FunctionScopeInfo * CurFn,const Decl * D,const ParentMap & PM)1172f4a2713aSLionel Sambuc static void diagnoseRepeatedUseOfWeak(Sema &S,
1173f4a2713aSLionel Sambuc                                       const sema::FunctionScopeInfo *CurFn,
1174f4a2713aSLionel Sambuc                                       const Decl *D,
1175f4a2713aSLionel Sambuc                                       const ParentMap &PM) {
1176f4a2713aSLionel Sambuc   typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1177f4a2713aSLionel Sambuc   typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1178f4a2713aSLionel Sambuc   typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1179*0a6a1f1dSLionel Sambuc   typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1180*0a6a1f1dSLionel Sambuc   StmtUsesPair;
1181f4a2713aSLionel Sambuc 
1182f4a2713aSLionel Sambuc   ASTContext &Ctx = S.getASTContext();
1183f4a2713aSLionel Sambuc 
1184f4a2713aSLionel Sambuc   const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1185f4a2713aSLionel Sambuc 
1186f4a2713aSLionel Sambuc   // Extract all weak objects that are referenced more than once.
1187f4a2713aSLionel Sambuc   SmallVector<StmtUsesPair, 8> UsesByStmt;
1188f4a2713aSLionel Sambuc   for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1189f4a2713aSLionel Sambuc        I != E; ++I) {
1190f4a2713aSLionel Sambuc     const WeakUseVector &Uses = I->second;
1191f4a2713aSLionel Sambuc 
1192f4a2713aSLionel Sambuc     // Find the first read of the weak object.
1193f4a2713aSLionel Sambuc     WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1194f4a2713aSLionel Sambuc     for ( ; UI != UE; ++UI) {
1195f4a2713aSLionel Sambuc       if (UI->isUnsafe())
1196f4a2713aSLionel Sambuc         break;
1197f4a2713aSLionel Sambuc     }
1198f4a2713aSLionel Sambuc 
1199f4a2713aSLionel Sambuc     // If there were only writes to this object, don't warn.
1200f4a2713aSLionel Sambuc     if (UI == UE)
1201f4a2713aSLionel Sambuc       continue;
1202f4a2713aSLionel Sambuc 
1203f4a2713aSLionel Sambuc     // If there was only one read, followed by any number of writes, and the
1204f4a2713aSLionel Sambuc     // read is not within a loop, don't warn. Additionally, don't warn in a
1205f4a2713aSLionel Sambuc     // loop if the base object is a local variable -- local variables are often
1206f4a2713aSLionel Sambuc     // changed in loops.
1207f4a2713aSLionel Sambuc     if (UI == Uses.begin()) {
1208f4a2713aSLionel Sambuc       WeakUseVector::const_iterator UI2 = UI;
1209f4a2713aSLionel Sambuc       for (++UI2; UI2 != UE; ++UI2)
1210f4a2713aSLionel Sambuc         if (UI2->isUnsafe())
1211f4a2713aSLionel Sambuc           break;
1212f4a2713aSLionel Sambuc 
1213f4a2713aSLionel Sambuc       if (UI2 == UE) {
1214f4a2713aSLionel Sambuc         if (!isInLoop(Ctx, PM, UI->getUseExpr()))
1215f4a2713aSLionel Sambuc           continue;
1216f4a2713aSLionel Sambuc 
1217f4a2713aSLionel Sambuc         const WeakObjectProfileTy &Profile = I->first;
1218f4a2713aSLionel Sambuc         if (!Profile.isExactProfile())
1219f4a2713aSLionel Sambuc           continue;
1220f4a2713aSLionel Sambuc 
1221f4a2713aSLionel Sambuc         const NamedDecl *Base = Profile.getBase();
1222f4a2713aSLionel Sambuc         if (!Base)
1223f4a2713aSLionel Sambuc           Base = Profile.getProperty();
1224f4a2713aSLionel Sambuc         assert(Base && "A profile always has a base or property.");
1225f4a2713aSLionel Sambuc 
1226f4a2713aSLionel Sambuc         if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1227f4a2713aSLionel Sambuc           if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1228f4a2713aSLionel Sambuc             continue;
1229f4a2713aSLionel Sambuc       }
1230f4a2713aSLionel Sambuc     }
1231f4a2713aSLionel Sambuc 
1232f4a2713aSLionel Sambuc     UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1233f4a2713aSLionel Sambuc   }
1234f4a2713aSLionel Sambuc 
1235f4a2713aSLionel Sambuc   if (UsesByStmt.empty())
1236f4a2713aSLionel Sambuc     return;
1237f4a2713aSLionel Sambuc 
1238f4a2713aSLionel Sambuc   // Sort by first use so that we emit the warnings in a deterministic order.
1239*0a6a1f1dSLionel Sambuc   SourceManager &SM = S.getSourceManager();
1240f4a2713aSLionel Sambuc   std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1241*0a6a1f1dSLionel Sambuc             [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1242*0a6a1f1dSLionel Sambuc     return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1243*0a6a1f1dSLionel Sambuc                                         RHS.first->getLocStart());
1244*0a6a1f1dSLionel Sambuc   });
1245f4a2713aSLionel Sambuc 
1246f4a2713aSLionel Sambuc   // Classify the current code body for better warning text.
1247f4a2713aSLionel Sambuc   // This enum should stay in sync with the cases in
1248f4a2713aSLionel Sambuc   // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1249f4a2713aSLionel Sambuc   // FIXME: Should we use a common classification enum and the same set of
1250f4a2713aSLionel Sambuc   // possibilities all throughout Sema?
1251f4a2713aSLionel Sambuc   enum {
1252f4a2713aSLionel Sambuc     Function,
1253f4a2713aSLionel Sambuc     Method,
1254f4a2713aSLionel Sambuc     Block,
1255f4a2713aSLionel Sambuc     Lambda
1256f4a2713aSLionel Sambuc   } FunctionKind;
1257f4a2713aSLionel Sambuc 
1258f4a2713aSLionel Sambuc   if (isa<sema::BlockScopeInfo>(CurFn))
1259f4a2713aSLionel Sambuc     FunctionKind = Block;
1260f4a2713aSLionel Sambuc   else if (isa<sema::LambdaScopeInfo>(CurFn))
1261f4a2713aSLionel Sambuc     FunctionKind = Lambda;
1262f4a2713aSLionel Sambuc   else if (isa<ObjCMethodDecl>(D))
1263f4a2713aSLionel Sambuc     FunctionKind = Method;
1264f4a2713aSLionel Sambuc   else
1265f4a2713aSLionel Sambuc     FunctionKind = Function;
1266f4a2713aSLionel Sambuc 
1267f4a2713aSLionel Sambuc   // Iterate through the sorted problems and emit warnings for each.
1268*0a6a1f1dSLionel Sambuc   for (const auto &P : UsesByStmt) {
1269*0a6a1f1dSLionel Sambuc     const Stmt *FirstRead = P.first;
1270*0a6a1f1dSLionel Sambuc     const WeakObjectProfileTy &Key = P.second->first;
1271*0a6a1f1dSLionel Sambuc     const WeakUseVector &Uses = P.second->second;
1272f4a2713aSLionel Sambuc 
1273f4a2713aSLionel Sambuc     // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1274f4a2713aSLionel Sambuc     // may not contain enough information to determine that these are different
1275f4a2713aSLionel Sambuc     // properties. We can only be 100% sure of a repeated use in certain cases,
1276f4a2713aSLionel Sambuc     // and we adjust the diagnostic kind accordingly so that the less certain
1277f4a2713aSLionel Sambuc     // case can be turned off if it is too noisy.
1278f4a2713aSLionel Sambuc     unsigned DiagKind;
1279f4a2713aSLionel Sambuc     if (Key.isExactProfile())
1280f4a2713aSLionel Sambuc       DiagKind = diag::warn_arc_repeated_use_of_weak;
1281f4a2713aSLionel Sambuc     else
1282f4a2713aSLionel Sambuc       DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1283f4a2713aSLionel Sambuc 
1284f4a2713aSLionel Sambuc     // Classify the weak object being accessed for better warning text.
1285f4a2713aSLionel Sambuc     // This enum should stay in sync with the cases in
1286f4a2713aSLionel Sambuc     // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1287f4a2713aSLionel Sambuc     enum {
1288f4a2713aSLionel Sambuc       Variable,
1289f4a2713aSLionel Sambuc       Property,
1290f4a2713aSLionel Sambuc       ImplicitProperty,
1291f4a2713aSLionel Sambuc       Ivar
1292f4a2713aSLionel Sambuc     } ObjectKind;
1293f4a2713aSLionel Sambuc 
1294f4a2713aSLionel Sambuc     const NamedDecl *D = Key.getProperty();
1295f4a2713aSLionel Sambuc     if (isa<VarDecl>(D))
1296f4a2713aSLionel Sambuc       ObjectKind = Variable;
1297f4a2713aSLionel Sambuc     else if (isa<ObjCPropertyDecl>(D))
1298f4a2713aSLionel Sambuc       ObjectKind = Property;
1299f4a2713aSLionel Sambuc     else if (isa<ObjCMethodDecl>(D))
1300f4a2713aSLionel Sambuc       ObjectKind = ImplicitProperty;
1301f4a2713aSLionel Sambuc     else if (isa<ObjCIvarDecl>(D))
1302f4a2713aSLionel Sambuc       ObjectKind = Ivar;
1303f4a2713aSLionel Sambuc     else
1304f4a2713aSLionel Sambuc       llvm_unreachable("Unexpected weak object kind!");
1305f4a2713aSLionel Sambuc 
1306f4a2713aSLionel Sambuc     // Show the first time the object was read.
1307f4a2713aSLionel Sambuc     S.Diag(FirstRead->getLocStart(), DiagKind)
1308f4a2713aSLionel Sambuc       << int(ObjectKind) << D << int(FunctionKind)
1309f4a2713aSLionel Sambuc       << FirstRead->getSourceRange();
1310f4a2713aSLionel Sambuc 
1311f4a2713aSLionel Sambuc     // Print all the other accesses as notes.
1312*0a6a1f1dSLionel Sambuc     for (const auto &Use : Uses) {
1313*0a6a1f1dSLionel Sambuc       if (Use.getUseExpr() == FirstRead)
1314f4a2713aSLionel Sambuc         continue;
1315*0a6a1f1dSLionel Sambuc       S.Diag(Use.getUseExpr()->getLocStart(),
1316f4a2713aSLionel Sambuc              diag::note_arc_weak_also_accessed_here)
1317*0a6a1f1dSLionel Sambuc           << Use.getUseExpr()->getSourceRange();
1318f4a2713aSLionel Sambuc     }
1319f4a2713aSLionel Sambuc   }
1320f4a2713aSLionel Sambuc }
1321f4a2713aSLionel Sambuc 
1322f4a2713aSLionel Sambuc namespace {
1323f4a2713aSLionel Sambuc class UninitValsDiagReporter : public UninitVariablesHandler {
1324f4a2713aSLionel Sambuc   Sema &S;
1325f4a2713aSLionel Sambuc   typedef SmallVector<UninitUse, 2> UsesVec;
1326f4a2713aSLionel Sambuc   typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1327f4a2713aSLionel Sambuc   // Prefer using MapVector to DenseMap, so that iteration order will be
1328f4a2713aSLionel Sambuc   // the same as insertion order. This is needed to obtain a deterministic
1329f4a2713aSLionel Sambuc   // order of diagnostics when calling flushDiagnostics().
1330f4a2713aSLionel Sambuc   typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1331f4a2713aSLionel Sambuc   UsesMap *uses;
1332f4a2713aSLionel Sambuc 
1333f4a2713aSLionel Sambuc public:
UninitValsDiagReporter(Sema & S)1334*0a6a1f1dSLionel Sambuc   UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
~UninitValsDiagReporter()1335f4a2713aSLionel Sambuc   ~UninitValsDiagReporter() {
1336f4a2713aSLionel Sambuc     flushDiagnostics();
1337f4a2713aSLionel Sambuc   }
1338f4a2713aSLionel Sambuc 
getUses(const VarDecl * vd)1339f4a2713aSLionel Sambuc   MappedType &getUses(const VarDecl *vd) {
1340f4a2713aSLionel Sambuc     if (!uses)
1341f4a2713aSLionel Sambuc       uses = new UsesMap();
1342f4a2713aSLionel Sambuc 
1343f4a2713aSLionel Sambuc     MappedType &V = (*uses)[vd];
1344f4a2713aSLionel Sambuc     if (!V.getPointer())
1345f4a2713aSLionel Sambuc       V.setPointer(new UsesVec());
1346f4a2713aSLionel Sambuc 
1347f4a2713aSLionel Sambuc     return V;
1348f4a2713aSLionel Sambuc   }
1349f4a2713aSLionel Sambuc 
handleUseOfUninitVariable(const VarDecl * vd,const UninitUse & use)1350*0a6a1f1dSLionel Sambuc   void handleUseOfUninitVariable(const VarDecl *vd,
1351*0a6a1f1dSLionel Sambuc                                  const UninitUse &use) override {
1352f4a2713aSLionel Sambuc     getUses(vd).getPointer()->push_back(use);
1353f4a2713aSLionel Sambuc   }
1354f4a2713aSLionel Sambuc 
handleSelfInit(const VarDecl * vd)1355*0a6a1f1dSLionel Sambuc   void handleSelfInit(const VarDecl *vd) override {
1356f4a2713aSLionel Sambuc     getUses(vd).setInt(true);
1357f4a2713aSLionel Sambuc   }
1358f4a2713aSLionel Sambuc 
flushDiagnostics()1359f4a2713aSLionel Sambuc   void flushDiagnostics() {
1360f4a2713aSLionel Sambuc     if (!uses)
1361f4a2713aSLionel Sambuc       return;
1362f4a2713aSLionel Sambuc 
1363*0a6a1f1dSLionel Sambuc     for (const auto &P : *uses) {
1364*0a6a1f1dSLionel Sambuc       const VarDecl *vd = P.first;
1365*0a6a1f1dSLionel Sambuc       const MappedType &V = P.second;
1366f4a2713aSLionel Sambuc 
1367f4a2713aSLionel Sambuc       UsesVec *vec = V.getPointer();
1368f4a2713aSLionel Sambuc       bool hasSelfInit = V.getInt();
1369f4a2713aSLionel Sambuc 
1370f4a2713aSLionel Sambuc       // Specially handle the case where we have uses of an uninitialized
1371f4a2713aSLionel Sambuc       // variable, but the root cause is an idiomatic self-init.  We want
1372f4a2713aSLionel Sambuc       // to report the diagnostic at the self-init since that is the root cause.
1373f4a2713aSLionel Sambuc       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1374f4a2713aSLionel Sambuc         DiagnoseUninitializedUse(S, vd,
1375f4a2713aSLionel Sambuc                                  UninitUse(vd->getInit()->IgnoreParenCasts(),
1376f4a2713aSLionel Sambuc                                            /* isAlwaysUninit */ true),
1377f4a2713aSLionel Sambuc                                  /* alwaysReportSelfInit */ true);
1378f4a2713aSLionel Sambuc       else {
1379f4a2713aSLionel Sambuc         // Sort the uses by their SourceLocations.  While not strictly
1380f4a2713aSLionel Sambuc         // guaranteed to produce them in line/column order, this will provide
1381f4a2713aSLionel Sambuc         // a stable ordering.
1382*0a6a1f1dSLionel Sambuc         std::sort(vec->begin(), vec->end(),
1383*0a6a1f1dSLionel Sambuc                   [](const UninitUse &a, const UninitUse &b) {
1384*0a6a1f1dSLionel Sambuc           // Prefer a more confident report over a less confident one.
1385*0a6a1f1dSLionel Sambuc           if (a.getKind() != b.getKind())
1386*0a6a1f1dSLionel Sambuc             return a.getKind() > b.getKind();
1387*0a6a1f1dSLionel Sambuc           return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1388*0a6a1f1dSLionel Sambuc         });
1389f4a2713aSLionel Sambuc 
1390*0a6a1f1dSLionel Sambuc         for (const auto &U : *vec) {
1391f4a2713aSLionel Sambuc           // If we have self-init, downgrade all uses to 'may be uninitialized'.
1392*0a6a1f1dSLionel Sambuc           UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1393f4a2713aSLionel Sambuc 
1394f4a2713aSLionel Sambuc           if (DiagnoseUninitializedUse(S, vd, Use))
1395f4a2713aSLionel Sambuc             // Skip further diagnostics for this variable. We try to warn only
1396f4a2713aSLionel Sambuc             // on the first point at which a variable is used uninitialized.
1397f4a2713aSLionel Sambuc             break;
1398f4a2713aSLionel Sambuc         }
1399f4a2713aSLionel Sambuc       }
1400f4a2713aSLionel Sambuc 
1401f4a2713aSLionel Sambuc       // Release the uses vector.
1402f4a2713aSLionel Sambuc       delete vec;
1403f4a2713aSLionel Sambuc     }
1404f4a2713aSLionel Sambuc     delete uses;
1405f4a2713aSLionel Sambuc   }
1406f4a2713aSLionel Sambuc 
1407f4a2713aSLionel Sambuc private:
hasAlwaysUninitializedUse(const UsesVec * vec)1408f4a2713aSLionel Sambuc   static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1409*0a6a1f1dSLionel Sambuc     return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1410*0a6a1f1dSLionel Sambuc       return U.getKind() == UninitUse::Always ||
1411*0a6a1f1dSLionel Sambuc              U.getKind() == UninitUse::AfterCall ||
1412*0a6a1f1dSLionel Sambuc              U.getKind() == UninitUse::AfterDecl;
1413*0a6a1f1dSLionel Sambuc     });
1414f4a2713aSLionel Sambuc   }
1415f4a2713aSLionel Sambuc };
1416f4a2713aSLionel Sambuc }
1417f4a2713aSLionel Sambuc 
1418f4a2713aSLionel Sambuc namespace clang {
1419f4a2713aSLionel Sambuc namespace {
1420f4a2713aSLionel Sambuc typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1421f4a2713aSLionel Sambuc typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1422f4a2713aSLionel Sambuc typedef std::list<DelayedDiag> DiagList;
1423f4a2713aSLionel Sambuc 
1424f4a2713aSLionel Sambuc struct SortDiagBySourceLocation {
1425f4a2713aSLionel Sambuc   SourceManager &SM;
SortDiagBySourceLocationclang::__anon895ab00e0c11::SortDiagBySourceLocation1426f4a2713aSLionel Sambuc   SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1427f4a2713aSLionel Sambuc 
operator ()clang::__anon895ab00e0c11::SortDiagBySourceLocation1428f4a2713aSLionel Sambuc   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1429f4a2713aSLionel Sambuc     // Although this call will be slow, this is only called when outputting
1430f4a2713aSLionel Sambuc     // multiple warnings.
1431f4a2713aSLionel Sambuc     return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1432f4a2713aSLionel Sambuc   }
1433f4a2713aSLionel Sambuc };
1434f4a2713aSLionel Sambuc }}
1435f4a2713aSLionel Sambuc 
1436f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1437f4a2713aSLionel Sambuc // -Wthread-safety
1438f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1439f4a2713aSLionel Sambuc namespace clang {
1440*0a6a1f1dSLionel Sambuc namespace threadSafety {
1441*0a6a1f1dSLionel Sambuc 
1442*0a6a1f1dSLionel Sambuc class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1443f4a2713aSLionel Sambuc   Sema &S;
1444f4a2713aSLionel Sambuc   DiagList Warnings;
1445f4a2713aSLionel Sambuc   SourceLocation FunLocation, FunEndLocation;
1446f4a2713aSLionel Sambuc 
1447*0a6a1f1dSLionel Sambuc   const FunctionDecl *CurrentFunction;
1448*0a6a1f1dSLionel Sambuc   bool Verbose;
1449*0a6a1f1dSLionel Sambuc 
getNotes() const1450*0a6a1f1dSLionel Sambuc   OptionalNotes getNotes() const {
1451*0a6a1f1dSLionel Sambuc     if (Verbose && CurrentFunction) {
1452*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1453*0a6a1f1dSLionel Sambuc                                 S.PDiag(diag::note_thread_warning_in_fun)
1454*0a6a1f1dSLionel Sambuc                                     << CurrentFunction->getNameAsString());
1455*0a6a1f1dSLionel Sambuc       return OptionalNotes(1, FNote);
1456*0a6a1f1dSLionel Sambuc     }
1457*0a6a1f1dSLionel Sambuc     return OptionalNotes();
1458*0a6a1f1dSLionel Sambuc   }
1459*0a6a1f1dSLionel Sambuc 
getNotes(const PartialDiagnosticAt & Note) const1460*0a6a1f1dSLionel Sambuc   OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1461*0a6a1f1dSLionel Sambuc     OptionalNotes ONS(1, Note);
1462*0a6a1f1dSLionel Sambuc     if (Verbose && CurrentFunction) {
1463*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1464*0a6a1f1dSLionel Sambuc                                 S.PDiag(diag::note_thread_warning_in_fun)
1465*0a6a1f1dSLionel Sambuc                                     << CurrentFunction->getNameAsString());
1466*0a6a1f1dSLionel Sambuc       ONS.push_back(FNote);
1467*0a6a1f1dSLionel Sambuc     }
1468*0a6a1f1dSLionel Sambuc     return ONS;
1469*0a6a1f1dSLionel Sambuc   }
1470*0a6a1f1dSLionel Sambuc 
getNotes(const PartialDiagnosticAt & Note1,const PartialDiagnosticAt & Note2) const1471*0a6a1f1dSLionel Sambuc   OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1472*0a6a1f1dSLionel Sambuc                          const PartialDiagnosticAt &Note2) const {
1473*0a6a1f1dSLionel Sambuc     OptionalNotes ONS;
1474*0a6a1f1dSLionel Sambuc     ONS.push_back(Note1);
1475*0a6a1f1dSLionel Sambuc     ONS.push_back(Note2);
1476*0a6a1f1dSLionel Sambuc     if (Verbose && CurrentFunction) {
1477*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1478*0a6a1f1dSLionel Sambuc                                 S.PDiag(diag::note_thread_warning_in_fun)
1479*0a6a1f1dSLionel Sambuc                                     << CurrentFunction->getNameAsString());
1480*0a6a1f1dSLionel Sambuc       ONS.push_back(FNote);
1481*0a6a1f1dSLionel Sambuc     }
1482*0a6a1f1dSLionel Sambuc     return ONS;
1483*0a6a1f1dSLionel Sambuc   }
1484*0a6a1f1dSLionel Sambuc 
1485f4a2713aSLionel Sambuc   // Helper functions
warnLockMismatch(unsigned DiagID,StringRef Kind,Name LockName,SourceLocation Loc)1486*0a6a1f1dSLionel Sambuc   void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1487*0a6a1f1dSLionel Sambuc                         SourceLocation Loc) {
1488f4a2713aSLionel Sambuc     // Gracefully handle rare cases when the analysis can't get a more
1489f4a2713aSLionel Sambuc     // precise source location.
1490f4a2713aSLionel Sambuc     if (!Loc.isValid())
1491f4a2713aSLionel Sambuc       Loc = FunLocation;
1492*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
1493*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1494f4a2713aSLionel Sambuc   }
1495f4a2713aSLionel Sambuc 
1496f4a2713aSLionel Sambuc  public:
ThreadSafetyReporter(Sema & S,SourceLocation FL,SourceLocation FEL)1497f4a2713aSLionel Sambuc   ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1498*0a6a1f1dSLionel Sambuc     : S(S), FunLocation(FL), FunEndLocation(FEL),
1499*0a6a1f1dSLionel Sambuc       CurrentFunction(nullptr), Verbose(false) {}
1500*0a6a1f1dSLionel Sambuc 
setVerbose(bool b)1501*0a6a1f1dSLionel Sambuc   void setVerbose(bool b) { Verbose = b; }
1502f4a2713aSLionel Sambuc 
1503f4a2713aSLionel Sambuc   /// \brief Emit all buffered diagnostics in order of sourcelocation.
1504f4a2713aSLionel Sambuc   /// We need to output diagnostics produced while iterating through
1505f4a2713aSLionel Sambuc   /// the lockset in deterministic order, so this function orders diagnostics
1506f4a2713aSLionel Sambuc   /// and outputs them.
emitDiagnostics()1507f4a2713aSLionel Sambuc   void emitDiagnostics() {
1508f4a2713aSLionel Sambuc     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1509*0a6a1f1dSLionel Sambuc     for (const auto &Diag : Warnings) {
1510*0a6a1f1dSLionel Sambuc       S.Diag(Diag.first.first, Diag.first.second);
1511*0a6a1f1dSLionel Sambuc       for (const auto &Note : Diag.second)
1512*0a6a1f1dSLionel Sambuc         S.Diag(Note.first, Note.second);
1513f4a2713aSLionel Sambuc     }
1514f4a2713aSLionel Sambuc   }
1515f4a2713aSLionel Sambuc 
handleInvalidLockExp(StringRef Kind,SourceLocation Loc)1516*0a6a1f1dSLionel Sambuc   void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1517*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1518*0a6a1f1dSLionel Sambuc                                          << Loc);
1519*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1520f4a2713aSLionel Sambuc   }
1521f4a2713aSLionel Sambuc 
handleUnmatchedUnlock(StringRef Kind,Name LockName,SourceLocation Loc)1522*0a6a1f1dSLionel Sambuc   void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1523*0a6a1f1dSLionel Sambuc                              SourceLocation Loc) override {
1524*0a6a1f1dSLionel Sambuc     warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1525f4a2713aSLionel Sambuc   }
1526f4a2713aSLionel Sambuc 
handleIncorrectUnlockKind(StringRef Kind,Name LockName,LockKind Expected,LockKind Received,SourceLocation Loc)1527*0a6a1f1dSLionel Sambuc   void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1528*0a6a1f1dSLionel Sambuc                                  LockKind Expected, LockKind Received,
1529*0a6a1f1dSLionel Sambuc                                  SourceLocation Loc) override {
1530*0a6a1f1dSLionel Sambuc     if (Loc.isInvalid())
1531*0a6a1f1dSLionel Sambuc       Loc = FunLocation;
1532*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
1533*0a6a1f1dSLionel Sambuc                                          << Kind << LockName << Received
1534*0a6a1f1dSLionel Sambuc                                          << Expected);
1535*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1536*0a6a1f1dSLionel Sambuc   }
1537*0a6a1f1dSLionel Sambuc 
handleDoubleLock(StringRef Kind,Name LockName,SourceLocation Loc)1538*0a6a1f1dSLionel Sambuc   void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1539*0a6a1f1dSLionel Sambuc     warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1540*0a6a1f1dSLionel Sambuc   }
1541*0a6a1f1dSLionel Sambuc 
handleMutexHeldEndOfScope(StringRef Kind,Name LockName,SourceLocation LocLocked,SourceLocation LocEndOfScope,LockErrorKind LEK)1542*0a6a1f1dSLionel Sambuc   void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1543*0a6a1f1dSLionel Sambuc                                  SourceLocation LocLocked,
1544f4a2713aSLionel Sambuc                                  SourceLocation LocEndOfScope,
1545*0a6a1f1dSLionel Sambuc                                  LockErrorKind LEK) override {
1546f4a2713aSLionel Sambuc     unsigned DiagID = 0;
1547f4a2713aSLionel Sambuc     switch (LEK) {
1548f4a2713aSLionel Sambuc       case LEK_LockedSomePredecessors:
1549f4a2713aSLionel Sambuc         DiagID = diag::warn_lock_some_predecessors;
1550f4a2713aSLionel Sambuc         break;
1551f4a2713aSLionel Sambuc       case LEK_LockedSomeLoopIterations:
1552f4a2713aSLionel Sambuc         DiagID = diag::warn_expecting_lock_held_on_loop;
1553f4a2713aSLionel Sambuc         break;
1554f4a2713aSLionel Sambuc       case LEK_LockedAtEndOfFunction:
1555f4a2713aSLionel Sambuc         DiagID = diag::warn_no_unlock;
1556f4a2713aSLionel Sambuc         break;
1557f4a2713aSLionel Sambuc       case LEK_NotLockedAtEndOfFunction:
1558f4a2713aSLionel Sambuc         DiagID = diag::warn_expecting_locked;
1559f4a2713aSLionel Sambuc         break;
1560f4a2713aSLionel Sambuc     }
1561f4a2713aSLionel Sambuc     if (LocEndOfScope.isInvalid())
1562f4a2713aSLionel Sambuc       LocEndOfScope = FunEndLocation;
1563f4a2713aSLionel Sambuc 
1564*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1565*0a6a1f1dSLionel Sambuc                                                                << LockName);
1566f4a2713aSLionel Sambuc     if (LocLocked.isValid()) {
1567*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1568*0a6a1f1dSLionel Sambuc                                               << Kind);
1569*0a6a1f1dSLionel Sambuc       Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
1570f4a2713aSLionel Sambuc       return;
1571f4a2713aSLionel Sambuc     }
1572*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1573f4a2713aSLionel Sambuc   }
1574f4a2713aSLionel Sambuc 
handleExclusiveAndShared(StringRef Kind,Name LockName,SourceLocation Loc1,SourceLocation Loc2)1575*0a6a1f1dSLionel Sambuc   void handleExclusiveAndShared(StringRef Kind, Name LockName,
1576*0a6a1f1dSLionel Sambuc                                 SourceLocation Loc1,
1577*0a6a1f1dSLionel Sambuc                                 SourceLocation Loc2) override {
1578*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(Loc1,
1579*0a6a1f1dSLionel Sambuc                                 S.PDiag(diag::warn_lock_exclusive_and_shared)
1580*0a6a1f1dSLionel Sambuc                                     << Kind << LockName);
1581*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1582*0a6a1f1dSLionel Sambuc                                        << Kind << LockName);
1583*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
1584f4a2713aSLionel Sambuc   }
1585f4a2713aSLionel Sambuc 
handleNoMutexHeld(StringRef Kind,const NamedDecl * D,ProtectedOperationKind POK,AccessKind AK,SourceLocation Loc)1586*0a6a1f1dSLionel Sambuc   void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1587*0a6a1f1dSLionel Sambuc                          ProtectedOperationKind POK, AccessKind AK,
1588*0a6a1f1dSLionel Sambuc                          SourceLocation Loc) override {
1589*0a6a1f1dSLionel Sambuc     assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1590*0a6a1f1dSLionel Sambuc            "Only works for variables");
1591f4a2713aSLionel Sambuc     unsigned DiagID = POK == POK_VarAccess?
1592f4a2713aSLionel Sambuc                         diag::warn_variable_requires_any_lock:
1593f4a2713aSLionel Sambuc                         diag::warn_var_deref_requires_any_lock;
1594f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1595f4a2713aSLionel Sambuc       << D->getNameAsString() << getLockKindFromAccessKind(AK));
1596*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1597f4a2713aSLionel Sambuc   }
1598f4a2713aSLionel Sambuc 
handleMutexNotHeld(StringRef Kind,const NamedDecl * D,ProtectedOperationKind POK,Name LockName,LockKind LK,SourceLocation Loc,Name * PossibleMatch)1599*0a6a1f1dSLionel Sambuc   void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1600*0a6a1f1dSLionel Sambuc                           ProtectedOperationKind POK, Name LockName,
1601*0a6a1f1dSLionel Sambuc                           LockKind LK, SourceLocation Loc,
1602*0a6a1f1dSLionel Sambuc                           Name *PossibleMatch) override {
1603f4a2713aSLionel Sambuc     unsigned DiagID = 0;
1604f4a2713aSLionel Sambuc     if (PossibleMatch) {
1605f4a2713aSLionel Sambuc       switch (POK) {
1606f4a2713aSLionel Sambuc         case POK_VarAccess:
1607f4a2713aSLionel Sambuc           DiagID = diag::warn_variable_requires_lock_precise;
1608f4a2713aSLionel Sambuc           break;
1609f4a2713aSLionel Sambuc         case POK_VarDereference:
1610f4a2713aSLionel Sambuc           DiagID = diag::warn_var_deref_requires_lock_precise;
1611f4a2713aSLionel Sambuc           break;
1612f4a2713aSLionel Sambuc         case POK_FunctionCall:
1613f4a2713aSLionel Sambuc           DiagID = diag::warn_fun_requires_lock_precise;
1614f4a2713aSLionel Sambuc           break;
1615*0a6a1f1dSLionel Sambuc         case POK_PassByRef:
1616*0a6a1f1dSLionel Sambuc           DiagID = diag::warn_guarded_pass_by_reference;
1617*0a6a1f1dSLionel Sambuc           break;
1618*0a6a1f1dSLionel Sambuc         case POK_PtPassByRef:
1619*0a6a1f1dSLionel Sambuc           DiagID = diag::warn_pt_guarded_pass_by_reference;
1620*0a6a1f1dSLionel Sambuc           break;
1621f4a2713aSLionel Sambuc       }
1622*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1623*0a6a1f1dSLionel Sambuc                                                        << D->getNameAsString()
1624*0a6a1f1dSLionel Sambuc                                                        << LockName << LK);
1625f4a2713aSLionel Sambuc       PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1626f4a2713aSLionel Sambuc                                         << *PossibleMatch);
1627*0a6a1f1dSLionel Sambuc       if (Verbose && POK == POK_VarAccess) {
1628*0a6a1f1dSLionel Sambuc         PartialDiagnosticAt VNote(D->getLocation(),
1629*0a6a1f1dSLionel Sambuc                                  S.PDiag(diag::note_guarded_by_declared_here)
1630*0a6a1f1dSLionel Sambuc                                      << D->getNameAsString());
1631*0a6a1f1dSLionel Sambuc         Warnings.push_back(DelayedDiag(Warning, getNotes(Note, VNote)));
1632*0a6a1f1dSLionel Sambuc       } else
1633*0a6a1f1dSLionel Sambuc         Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
1634f4a2713aSLionel Sambuc     } else {
1635f4a2713aSLionel Sambuc       switch (POK) {
1636f4a2713aSLionel Sambuc         case POK_VarAccess:
1637f4a2713aSLionel Sambuc           DiagID = diag::warn_variable_requires_lock;
1638f4a2713aSLionel Sambuc           break;
1639f4a2713aSLionel Sambuc         case POK_VarDereference:
1640f4a2713aSLionel Sambuc           DiagID = diag::warn_var_deref_requires_lock;
1641f4a2713aSLionel Sambuc           break;
1642f4a2713aSLionel Sambuc         case POK_FunctionCall:
1643f4a2713aSLionel Sambuc           DiagID = diag::warn_fun_requires_lock;
1644f4a2713aSLionel Sambuc           break;
1645*0a6a1f1dSLionel Sambuc         case POK_PassByRef:
1646*0a6a1f1dSLionel Sambuc           DiagID = diag::warn_guarded_pass_by_reference;
1647*0a6a1f1dSLionel Sambuc           break;
1648*0a6a1f1dSLionel Sambuc         case POK_PtPassByRef:
1649*0a6a1f1dSLionel Sambuc           DiagID = diag::warn_pt_guarded_pass_by_reference;
1650*0a6a1f1dSLionel Sambuc           break;
1651f4a2713aSLionel Sambuc       }
1652*0a6a1f1dSLionel Sambuc       PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1653*0a6a1f1dSLionel Sambuc                                                        << D->getNameAsString()
1654*0a6a1f1dSLionel Sambuc                                                        << LockName << LK);
1655*0a6a1f1dSLionel Sambuc       if (Verbose && POK == POK_VarAccess) {
1656*0a6a1f1dSLionel Sambuc         PartialDiagnosticAt Note(D->getLocation(),
1657*0a6a1f1dSLionel Sambuc                                  S.PDiag(diag::note_guarded_by_declared_here)
1658*0a6a1f1dSLionel Sambuc                                      << D->getNameAsString());
1659*0a6a1f1dSLionel Sambuc         Warnings.push_back(DelayedDiag(Warning, getNotes(Note)));
1660*0a6a1f1dSLionel Sambuc       } else
1661*0a6a1f1dSLionel Sambuc         Warnings.push_back(DelayedDiag(Warning, getNotes()));
1662f4a2713aSLionel Sambuc     }
1663f4a2713aSLionel Sambuc   }
1664f4a2713aSLionel Sambuc 
1665*0a6a1f1dSLionel Sambuc 
handleNegativeNotHeld(StringRef Kind,Name LockName,Name Neg,SourceLocation Loc)1666*0a6a1f1dSLionel Sambuc   virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1667*0a6a1f1dSLionel Sambuc                                      SourceLocation Loc) override {
1668f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc,
1669*0a6a1f1dSLionel Sambuc         S.PDiag(diag::warn_acquire_requires_negative_cap)
1670*0a6a1f1dSLionel Sambuc         << Kind << LockName << Neg);
1671*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1672*0a6a1f1dSLionel Sambuc   }
1673*0a6a1f1dSLionel Sambuc 
1674*0a6a1f1dSLionel Sambuc 
handleFunExcludesLock(StringRef Kind,Name FunName,Name LockName,SourceLocation Loc)1675*0a6a1f1dSLionel Sambuc   void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1676*0a6a1f1dSLionel Sambuc                              SourceLocation Loc) override {
1677*0a6a1f1dSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1678*0a6a1f1dSLionel Sambuc                                          << Kind << FunName << LockName);
1679*0a6a1f1dSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, getNotes()));
1680*0a6a1f1dSLionel Sambuc   }
1681*0a6a1f1dSLionel Sambuc 
enterFunction(const FunctionDecl * FD)1682*0a6a1f1dSLionel Sambuc   void enterFunction(const FunctionDecl* FD) override {
1683*0a6a1f1dSLionel Sambuc     CurrentFunction = FD;
1684*0a6a1f1dSLionel Sambuc   }
1685*0a6a1f1dSLionel Sambuc 
leaveFunction(const FunctionDecl * FD)1686*0a6a1f1dSLionel Sambuc   void leaveFunction(const FunctionDecl* FD) override {
1687*0a6a1f1dSLionel Sambuc     CurrentFunction = 0;
1688f4a2713aSLionel Sambuc   }
1689f4a2713aSLionel Sambuc };
1690*0a6a1f1dSLionel Sambuc 
1691f4a2713aSLionel Sambuc }
1692f4a2713aSLionel Sambuc }
1693f4a2713aSLionel Sambuc 
1694f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1695f4a2713aSLionel Sambuc // -Wconsumed
1696f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1697f4a2713aSLionel Sambuc 
1698f4a2713aSLionel Sambuc namespace clang {
1699f4a2713aSLionel Sambuc namespace consumed {
1700f4a2713aSLionel Sambuc namespace {
1701f4a2713aSLionel Sambuc class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1702f4a2713aSLionel Sambuc 
1703f4a2713aSLionel Sambuc   Sema &S;
1704f4a2713aSLionel Sambuc   DiagList Warnings;
1705f4a2713aSLionel Sambuc 
1706f4a2713aSLionel Sambuc public:
1707f4a2713aSLionel Sambuc 
ConsumedWarningsHandler(Sema & S)1708f4a2713aSLionel Sambuc   ConsumedWarningsHandler(Sema &S) : S(S) {}
1709f4a2713aSLionel Sambuc 
emitDiagnostics()1710*0a6a1f1dSLionel Sambuc   void emitDiagnostics() override {
1711f4a2713aSLionel Sambuc     Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1712*0a6a1f1dSLionel Sambuc     for (const auto &Diag : Warnings) {
1713*0a6a1f1dSLionel Sambuc       S.Diag(Diag.first.first, Diag.first.second);
1714*0a6a1f1dSLionel Sambuc       for (const auto &Note : Diag.second)
1715*0a6a1f1dSLionel Sambuc         S.Diag(Note.first, Note.second);
1716f4a2713aSLionel Sambuc     }
1717f4a2713aSLionel Sambuc   }
1718f4a2713aSLionel Sambuc 
warnLoopStateMismatch(SourceLocation Loc,StringRef VariableName)1719*0a6a1f1dSLionel Sambuc   void warnLoopStateMismatch(SourceLocation Loc,
1720*0a6a1f1dSLionel Sambuc                              StringRef VariableName) override {
1721f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1722f4a2713aSLionel Sambuc       VariableName);
1723f4a2713aSLionel Sambuc 
1724f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1725f4a2713aSLionel Sambuc   }
1726f4a2713aSLionel Sambuc 
warnParamReturnTypestateMismatch(SourceLocation Loc,StringRef VariableName,StringRef ExpectedState,StringRef ObservedState)1727f4a2713aSLionel Sambuc   void warnParamReturnTypestateMismatch(SourceLocation Loc,
1728f4a2713aSLionel Sambuc                                         StringRef VariableName,
1729f4a2713aSLionel Sambuc                                         StringRef ExpectedState,
1730*0a6a1f1dSLionel Sambuc                                         StringRef ObservedState) override {
1731f4a2713aSLionel Sambuc 
1732f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(
1733f4a2713aSLionel Sambuc       diag::warn_param_return_typestate_mismatch) << VariableName <<
1734f4a2713aSLionel Sambuc         ExpectedState << ObservedState);
1735f4a2713aSLionel Sambuc 
1736f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1737f4a2713aSLionel Sambuc   }
1738f4a2713aSLionel Sambuc 
warnParamTypestateMismatch(SourceLocation Loc,StringRef ExpectedState,StringRef ObservedState)1739f4a2713aSLionel Sambuc   void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1740*0a6a1f1dSLionel Sambuc                                   StringRef ObservedState) override {
1741f4a2713aSLionel Sambuc 
1742f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(
1743f4a2713aSLionel Sambuc       diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1744f4a2713aSLionel Sambuc 
1745f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1746f4a2713aSLionel Sambuc   }
1747f4a2713aSLionel Sambuc 
warnReturnTypestateForUnconsumableType(SourceLocation Loc,StringRef TypeName)1748f4a2713aSLionel Sambuc   void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
1749*0a6a1f1dSLionel Sambuc                                               StringRef TypeName) override {
1750f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(
1751f4a2713aSLionel Sambuc       diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1752f4a2713aSLionel Sambuc 
1753f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1754f4a2713aSLionel Sambuc   }
1755f4a2713aSLionel Sambuc 
warnReturnTypestateMismatch(SourceLocation Loc,StringRef ExpectedState,StringRef ObservedState)1756f4a2713aSLionel Sambuc   void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
1757*0a6a1f1dSLionel Sambuc                                    StringRef ObservedState) override {
1758f4a2713aSLionel Sambuc 
1759f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(
1760f4a2713aSLionel Sambuc       diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1761f4a2713aSLionel Sambuc 
1762f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1763f4a2713aSLionel Sambuc   }
1764f4a2713aSLionel Sambuc 
warnUseOfTempInInvalidState(StringRef MethodName,StringRef State,SourceLocation Loc)1765f4a2713aSLionel Sambuc   void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
1766*0a6a1f1dSLionel Sambuc                                    SourceLocation Loc) override {
1767f4a2713aSLionel Sambuc 
1768f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(
1769f4a2713aSLionel Sambuc       diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
1770f4a2713aSLionel Sambuc 
1771f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1772f4a2713aSLionel Sambuc   }
1773f4a2713aSLionel Sambuc 
warnUseInInvalidState(StringRef MethodName,StringRef VariableName,StringRef State,SourceLocation Loc)1774f4a2713aSLionel Sambuc   void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1775*0a6a1f1dSLionel Sambuc                              StringRef State, SourceLocation Loc) override {
1776f4a2713aSLionel Sambuc 
1777f4a2713aSLionel Sambuc     PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1778f4a2713aSLionel Sambuc                                 MethodName << VariableName << State);
1779f4a2713aSLionel Sambuc 
1780f4a2713aSLionel Sambuc     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1781f4a2713aSLionel Sambuc   }
1782f4a2713aSLionel Sambuc };
1783f4a2713aSLionel Sambuc }}}
1784f4a2713aSLionel Sambuc 
1785f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1786f4a2713aSLionel Sambuc // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1787f4a2713aSLionel Sambuc //  warnings on a function, method, or block.
1788f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
1789f4a2713aSLionel Sambuc 
Policy()1790f4a2713aSLionel Sambuc clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1791f4a2713aSLionel Sambuc   enableCheckFallThrough = 1;
1792f4a2713aSLionel Sambuc   enableCheckUnreachable = 0;
1793f4a2713aSLionel Sambuc   enableThreadSafetyAnalysis = 0;
1794f4a2713aSLionel Sambuc   enableConsumedAnalysis = 0;
1795f4a2713aSLionel Sambuc }
1796f4a2713aSLionel Sambuc 
isEnabled(DiagnosticsEngine & D,unsigned diag)1797*0a6a1f1dSLionel Sambuc static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1798*0a6a1f1dSLionel Sambuc   return (unsigned)!D.isIgnored(diag, SourceLocation());
1799*0a6a1f1dSLionel Sambuc }
1800*0a6a1f1dSLionel Sambuc 
AnalysisBasedWarnings(Sema & s)1801f4a2713aSLionel Sambuc clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1802f4a2713aSLionel Sambuc   : S(s),
1803f4a2713aSLionel Sambuc     NumFunctionsAnalyzed(0),
1804f4a2713aSLionel Sambuc     NumFunctionsWithBadCFGs(0),
1805f4a2713aSLionel Sambuc     NumCFGBlocks(0),
1806f4a2713aSLionel Sambuc     MaxCFGBlocksPerFunction(0),
1807f4a2713aSLionel Sambuc     NumUninitAnalysisFunctions(0),
1808f4a2713aSLionel Sambuc     NumUninitAnalysisVariables(0),
1809f4a2713aSLionel Sambuc     MaxUninitAnalysisVariablesPerFunction(0),
1810f4a2713aSLionel Sambuc     NumUninitAnalysisBlockVisits(0),
1811f4a2713aSLionel Sambuc     MaxUninitAnalysisBlockVisitsPerFunction(0) {
1812*0a6a1f1dSLionel Sambuc 
1813*0a6a1f1dSLionel Sambuc   using namespace diag;
1814f4a2713aSLionel Sambuc   DiagnosticsEngine &D = S.getDiagnostics();
1815*0a6a1f1dSLionel Sambuc 
1816*0a6a1f1dSLionel Sambuc   DefaultPolicy.enableCheckUnreachable =
1817*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_unreachable) ||
1818*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_unreachable_break) ||
1819*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_unreachable_return) ||
1820*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_unreachable_loop_increment);
1821*0a6a1f1dSLionel Sambuc 
1822*0a6a1f1dSLionel Sambuc   DefaultPolicy.enableThreadSafetyAnalysis =
1823*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_double_lock);
1824*0a6a1f1dSLionel Sambuc 
1825*0a6a1f1dSLionel Sambuc   DefaultPolicy.enableConsumedAnalysis =
1826*0a6a1f1dSLionel Sambuc     isEnabled(D, warn_use_in_invalid_state);
1827f4a2713aSLionel Sambuc }
1828f4a2713aSLionel Sambuc 
flushDiagnostics(Sema & S,const sema::FunctionScopeInfo * fscope)1829*0a6a1f1dSLionel Sambuc static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1830*0a6a1f1dSLionel Sambuc   for (const auto &D : fscope->PossiblyUnreachableDiags)
1831f4a2713aSLionel Sambuc     S.Diag(D.Loc, D.PD);
1832f4a2713aSLionel Sambuc }
1833f4a2713aSLionel Sambuc 
1834f4a2713aSLionel Sambuc void clang::sema::
IssueWarnings(sema::AnalysisBasedWarnings::Policy P,sema::FunctionScopeInfo * fscope,const Decl * D,const BlockExpr * blkExpr)1835f4a2713aSLionel Sambuc AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1836f4a2713aSLionel Sambuc                                      sema::FunctionScopeInfo *fscope,
1837f4a2713aSLionel Sambuc                                      const Decl *D, const BlockExpr *blkExpr) {
1838f4a2713aSLionel Sambuc 
1839f4a2713aSLionel Sambuc   // We avoid doing analysis-based warnings when there are errors for
1840f4a2713aSLionel Sambuc   // two reasons:
1841f4a2713aSLionel Sambuc   // (1) The CFGs often can't be constructed (if the body is invalid), so
1842f4a2713aSLionel Sambuc   //     don't bother trying.
1843f4a2713aSLionel Sambuc   // (2) The code already has problems; running the analysis just takes more
1844f4a2713aSLionel Sambuc   //     time.
1845f4a2713aSLionel Sambuc   DiagnosticsEngine &Diags = S.getDiagnostics();
1846f4a2713aSLionel Sambuc 
1847f4a2713aSLionel Sambuc   // Do not do any analysis for declarations in system headers if we are
1848f4a2713aSLionel Sambuc   // going to just ignore them.
1849f4a2713aSLionel Sambuc   if (Diags.getSuppressSystemWarnings() &&
1850f4a2713aSLionel Sambuc       S.SourceMgr.isInSystemHeader(D->getLocation()))
1851f4a2713aSLionel Sambuc     return;
1852f4a2713aSLionel Sambuc 
1853f4a2713aSLionel Sambuc   // For code in dependent contexts, we'll do this at instantiation time.
1854f4a2713aSLionel Sambuc   if (cast<DeclContext>(D)->isDependentContext())
1855f4a2713aSLionel Sambuc     return;
1856f4a2713aSLionel Sambuc 
1857f4a2713aSLionel Sambuc   if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1858f4a2713aSLionel Sambuc     // Flush out any possibly unreachable diagnostics.
1859f4a2713aSLionel Sambuc     flushDiagnostics(S, fscope);
1860f4a2713aSLionel Sambuc     return;
1861f4a2713aSLionel Sambuc   }
1862f4a2713aSLionel Sambuc 
1863f4a2713aSLionel Sambuc   const Stmt *Body = D->getBody();
1864f4a2713aSLionel Sambuc   assert(Body);
1865f4a2713aSLionel Sambuc 
1866f4a2713aSLionel Sambuc   // Construct the analysis context with the specified CFG build options.
1867*0a6a1f1dSLionel Sambuc   AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
1868f4a2713aSLionel Sambuc 
1869f4a2713aSLionel Sambuc   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1870f4a2713aSLionel Sambuc   // explosion for destructors that can result and the compile time hit.
1871f4a2713aSLionel Sambuc   AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1872f4a2713aSLionel Sambuc   AC.getCFGBuildOptions().AddEHEdges = false;
1873f4a2713aSLionel Sambuc   AC.getCFGBuildOptions().AddInitializers = true;
1874f4a2713aSLionel Sambuc   AC.getCFGBuildOptions().AddImplicitDtors = true;
1875f4a2713aSLionel Sambuc   AC.getCFGBuildOptions().AddTemporaryDtors = true;
1876*0a6a1f1dSLionel Sambuc   AC.getCFGBuildOptions().AddCXXNewAllocator = false;
1877f4a2713aSLionel Sambuc 
1878f4a2713aSLionel Sambuc   // Force that certain expressions appear as CFGElements in the CFG.  This
1879f4a2713aSLionel Sambuc   // is used to speed up various analyses.
1880f4a2713aSLionel Sambuc   // FIXME: This isn't the right factoring.  This is here for initial
1881f4a2713aSLionel Sambuc   // prototyping, but we need a way for analyses to say what expressions they
1882f4a2713aSLionel Sambuc   // expect to always be CFGElements and then fill in the BuildOptions
1883f4a2713aSLionel Sambuc   // appropriately.  This is essentially a layering violation.
1884f4a2713aSLionel Sambuc   if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1885f4a2713aSLionel Sambuc       P.enableConsumedAnalysis) {
1886f4a2713aSLionel Sambuc     // Unreachable code analysis and thread safety require a linearized CFG.
1887f4a2713aSLionel Sambuc     AC.getCFGBuildOptions().setAllAlwaysAdd();
1888f4a2713aSLionel Sambuc   }
1889f4a2713aSLionel Sambuc   else {
1890f4a2713aSLionel Sambuc     AC.getCFGBuildOptions()
1891f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::BinaryOperatorClass)
1892f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1893f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::BlockExprClass)
1894f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::CStyleCastExprClass)
1895f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::DeclRefExprClass)
1896f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1897f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::UnaryOperatorClass)
1898f4a2713aSLionel Sambuc       .setAlwaysAdd(Stmt::AttributedStmtClass);
1899f4a2713aSLionel Sambuc   }
1900f4a2713aSLionel Sambuc 
1901*0a6a1f1dSLionel Sambuc   // Install the logical handler for -Wtautological-overlap-compare
1902*0a6a1f1dSLionel Sambuc   std::unique_ptr<LogicalErrorHandler> LEH;
1903*0a6a1f1dSLionel Sambuc   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1904*0a6a1f1dSLionel Sambuc                        D->getLocStart())) {
1905*0a6a1f1dSLionel Sambuc     LEH.reset(new LogicalErrorHandler(S));
1906*0a6a1f1dSLionel Sambuc     AC.getCFGBuildOptions().Observer = LEH.get();
1907*0a6a1f1dSLionel Sambuc   }
1908f4a2713aSLionel Sambuc 
1909f4a2713aSLionel Sambuc   // Emit delayed diagnostics.
1910f4a2713aSLionel Sambuc   if (!fscope->PossiblyUnreachableDiags.empty()) {
1911f4a2713aSLionel Sambuc     bool analyzed = false;
1912f4a2713aSLionel Sambuc 
1913f4a2713aSLionel Sambuc     // Register the expressions with the CFGBuilder.
1914*0a6a1f1dSLionel Sambuc     for (const auto &D : fscope->PossiblyUnreachableDiags) {
1915*0a6a1f1dSLionel Sambuc       if (D.stmt)
1916*0a6a1f1dSLionel Sambuc         AC.registerForcedBlockExpression(D.stmt);
1917f4a2713aSLionel Sambuc     }
1918f4a2713aSLionel Sambuc 
1919f4a2713aSLionel Sambuc     if (AC.getCFG()) {
1920f4a2713aSLionel Sambuc       analyzed = true;
1921*0a6a1f1dSLionel Sambuc       for (const auto &D : fscope->PossiblyUnreachableDiags) {
1922f4a2713aSLionel Sambuc         bool processed = false;
1923*0a6a1f1dSLionel Sambuc         if (D.stmt) {
1924*0a6a1f1dSLionel Sambuc           const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
1925f4a2713aSLionel Sambuc           CFGReverseBlockReachabilityAnalysis *cra =
1926f4a2713aSLionel Sambuc               AC.getCFGReachablityAnalysis();
1927f4a2713aSLionel Sambuc           // FIXME: We should be able to assert that block is non-null, but
1928f4a2713aSLionel Sambuc           // the CFG analysis can skip potentially-evaluated expressions in
1929f4a2713aSLionel Sambuc           // edge cases; see test/Sema/vla-2.c.
1930f4a2713aSLionel Sambuc           if (block && cra) {
1931f4a2713aSLionel Sambuc             // Can this block be reached from the entrance?
1932f4a2713aSLionel Sambuc             if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1933f4a2713aSLionel Sambuc               S.Diag(D.Loc, D.PD);
1934f4a2713aSLionel Sambuc             processed = true;
1935f4a2713aSLionel Sambuc           }
1936f4a2713aSLionel Sambuc         }
1937f4a2713aSLionel Sambuc         if (!processed) {
1938f4a2713aSLionel Sambuc           // Emit the warning anyway if we cannot map to a basic block.
1939f4a2713aSLionel Sambuc           S.Diag(D.Loc, D.PD);
1940f4a2713aSLionel Sambuc         }
1941f4a2713aSLionel Sambuc       }
1942f4a2713aSLionel Sambuc     }
1943f4a2713aSLionel Sambuc 
1944f4a2713aSLionel Sambuc     if (!analyzed)
1945f4a2713aSLionel Sambuc       flushDiagnostics(S, fscope);
1946f4a2713aSLionel Sambuc   }
1947f4a2713aSLionel Sambuc 
1948f4a2713aSLionel Sambuc 
1949f4a2713aSLionel Sambuc   // Warning: check missing 'return'
1950f4a2713aSLionel Sambuc   if (P.enableCheckFallThrough) {
1951f4a2713aSLionel Sambuc     const CheckFallThroughDiagnostics &CD =
1952f4a2713aSLionel Sambuc       (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1953f4a2713aSLionel Sambuc        : (isa<CXXMethodDecl>(D) &&
1954f4a2713aSLionel Sambuc           cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1955f4a2713aSLionel Sambuc           cast<CXXMethodDecl>(D)->getParent()->isLambda())
1956f4a2713aSLionel Sambuc             ? CheckFallThroughDiagnostics::MakeForLambda()
1957f4a2713aSLionel Sambuc             : CheckFallThroughDiagnostics::MakeForFunction(D));
1958f4a2713aSLionel Sambuc     CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1959f4a2713aSLionel Sambuc   }
1960f4a2713aSLionel Sambuc 
1961f4a2713aSLionel Sambuc   // Warning: check for unreachable code
1962f4a2713aSLionel Sambuc   if (P.enableCheckUnreachable) {
1963f4a2713aSLionel Sambuc     // Only check for unreachable code on non-template instantiations.
1964f4a2713aSLionel Sambuc     // Different template instantiations can effectively change the control-flow
1965f4a2713aSLionel Sambuc     // and it is very difficult to prove that a snippet of code in a template
1966f4a2713aSLionel Sambuc     // is unreachable for all instantiations.
1967f4a2713aSLionel Sambuc     bool isTemplateInstantiation = false;
1968f4a2713aSLionel Sambuc     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1969f4a2713aSLionel Sambuc       isTemplateInstantiation = Function->isTemplateInstantiation();
1970f4a2713aSLionel Sambuc     if (!isTemplateInstantiation)
1971f4a2713aSLionel Sambuc       CheckUnreachable(S, AC);
1972f4a2713aSLionel Sambuc   }
1973f4a2713aSLionel Sambuc 
1974f4a2713aSLionel Sambuc   // Check for thread safety violations
1975f4a2713aSLionel Sambuc   if (P.enableThreadSafetyAnalysis) {
1976f4a2713aSLionel Sambuc     SourceLocation FL = AC.getDecl()->getLocation();
1977f4a2713aSLionel Sambuc     SourceLocation FEL = AC.getDecl()->getLocEnd();
1978*0a6a1f1dSLionel Sambuc     threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
1979*0a6a1f1dSLionel Sambuc     if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
1980f4a2713aSLionel Sambuc       Reporter.setIssueBetaWarnings(true);
1981*0a6a1f1dSLionel Sambuc     if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
1982*0a6a1f1dSLionel Sambuc       Reporter.setVerbose(true);
1983f4a2713aSLionel Sambuc 
1984*0a6a1f1dSLionel Sambuc     threadSafety::runThreadSafetyAnalysis(AC, Reporter);
1985f4a2713aSLionel Sambuc     Reporter.emitDiagnostics();
1986f4a2713aSLionel Sambuc   }
1987f4a2713aSLionel Sambuc 
1988f4a2713aSLionel Sambuc   // Check for violations of consumed properties.
1989f4a2713aSLionel Sambuc   if (P.enableConsumedAnalysis) {
1990f4a2713aSLionel Sambuc     consumed::ConsumedWarningsHandler WarningHandler(S);
1991f4a2713aSLionel Sambuc     consumed::ConsumedAnalyzer Analyzer(WarningHandler);
1992f4a2713aSLionel Sambuc     Analyzer.run(AC);
1993f4a2713aSLionel Sambuc   }
1994f4a2713aSLionel Sambuc 
1995*0a6a1f1dSLionel Sambuc   if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
1996*0a6a1f1dSLionel Sambuc       !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
1997*0a6a1f1dSLionel Sambuc       !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
1998f4a2713aSLionel Sambuc     if (CFG *cfg = AC.getCFG()) {
1999f4a2713aSLionel Sambuc       UninitValsDiagReporter reporter(S);
2000f4a2713aSLionel Sambuc       UninitVariablesAnalysisStats stats;
2001f4a2713aSLionel Sambuc       std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
2002f4a2713aSLionel Sambuc       runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
2003f4a2713aSLionel Sambuc                                         reporter, stats);
2004f4a2713aSLionel Sambuc 
2005f4a2713aSLionel Sambuc       if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2006f4a2713aSLionel Sambuc         ++NumUninitAnalysisFunctions;
2007f4a2713aSLionel Sambuc         NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2008f4a2713aSLionel Sambuc         NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2009f4a2713aSLionel Sambuc         MaxUninitAnalysisVariablesPerFunction =
2010f4a2713aSLionel Sambuc             std::max(MaxUninitAnalysisVariablesPerFunction,
2011f4a2713aSLionel Sambuc                      stats.NumVariablesAnalyzed);
2012f4a2713aSLionel Sambuc         MaxUninitAnalysisBlockVisitsPerFunction =
2013f4a2713aSLionel Sambuc             std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2014f4a2713aSLionel Sambuc                      stats.NumBlockVisits);
2015f4a2713aSLionel Sambuc       }
2016f4a2713aSLionel Sambuc     }
2017f4a2713aSLionel Sambuc   }
2018f4a2713aSLionel Sambuc 
2019f4a2713aSLionel Sambuc   bool FallThroughDiagFull =
2020*0a6a1f1dSLionel Sambuc       !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2021*0a6a1f1dSLionel Sambuc   bool FallThroughDiagPerFunction = !Diags.isIgnored(
2022*0a6a1f1dSLionel Sambuc       diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
2023f4a2713aSLionel Sambuc   if (FallThroughDiagFull || FallThroughDiagPerFunction) {
2024f4a2713aSLionel Sambuc     DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
2025f4a2713aSLionel Sambuc   }
2026f4a2713aSLionel Sambuc 
2027f4a2713aSLionel Sambuc   if (S.getLangOpts().ObjCARCWeak &&
2028*0a6a1f1dSLionel Sambuc       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
2029f4a2713aSLionel Sambuc     diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
2030f4a2713aSLionel Sambuc 
2031*0a6a1f1dSLionel Sambuc 
2032*0a6a1f1dSLionel Sambuc   // Check for infinite self-recursion in functions
2033*0a6a1f1dSLionel Sambuc   if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2034*0a6a1f1dSLionel Sambuc                        D->getLocStart())) {
2035*0a6a1f1dSLionel Sambuc     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2036*0a6a1f1dSLionel Sambuc       checkRecursiveFunction(S, FD, Body, AC);
2037*0a6a1f1dSLionel Sambuc     }
2038*0a6a1f1dSLionel Sambuc   }
2039*0a6a1f1dSLionel Sambuc 
2040*0a6a1f1dSLionel Sambuc   // If none of the previous checks caused a CFG build, trigger one here
2041*0a6a1f1dSLionel Sambuc   // for -Wtautological-overlap-compare
2042*0a6a1f1dSLionel Sambuc   if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2043*0a6a1f1dSLionel Sambuc                                D->getLocStart())) {
2044*0a6a1f1dSLionel Sambuc     AC.getCFG();
2045*0a6a1f1dSLionel Sambuc   }
2046*0a6a1f1dSLionel Sambuc 
2047f4a2713aSLionel Sambuc   // Collect statistics about the CFG if it was built.
2048f4a2713aSLionel Sambuc   if (S.CollectStats && AC.isCFGBuilt()) {
2049f4a2713aSLionel Sambuc     ++NumFunctionsAnalyzed;
2050f4a2713aSLionel Sambuc     if (CFG *cfg = AC.getCFG()) {
2051f4a2713aSLionel Sambuc       // If we successfully built a CFG for this context, record some more
2052f4a2713aSLionel Sambuc       // detail information about it.
2053f4a2713aSLionel Sambuc       NumCFGBlocks += cfg->getNumBlockIDs();
2054f4a2713aSLionel Sambuc       MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2055f4a2713aSLionel Sambuc                                          cfg->getNumBlockIDs());
2056f4a2713aSLionel Sambuc     } else {
2057f4a2713aSLionel Sambuc       ++NumFunctionsWithBadCFGs;
2058f4a2713aSLionel Sambuc     }
2059f4a2713aSLionel Sambuc   }
2060f4a2713aSLionel Sambuc }
2061f4a2713aSLionel Sambuc 
PrintStats() const2062f4a2713aSLionel Sambuc void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2063f4a2713aSLionel Sambuc   llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2064f4a2713aSLionel Sambuc 
2065f4a2713aSLionel Sambuc   unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2066f4a2713aSLionel Sambuc   unsigned AvgCFGBlocksPerFunction =
2067f4a2713aSLionel Sambuc       !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2068f4a2713aSLionel Sambuc   llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2069f4a2713aSLionel Sambuc                << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2070f4a2713aSLionel Sambuc                << "  " << NumCFGBlocks << " CFG blocks built.\n"
2071f4a2713aSLionel Sambuc                << "  " << AvgCFGBlocksPerFunction
2072f4a2713aSLionel Sambuc                << " average CFG blocks per function.\n"
2073f4a2713aSLionel Sambuc                << "  " << MaxCFGBlocksPerFunction
2074f4a2713aSLionel Sambuc                << " max CFG blocks per function.\n";
2075f4a2713aSLionel Sambuc 
2076f4a2713aSLionel Sambuc   unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2077f4a2713aSLionel Sambuc       : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2078f4a2713aSLionel Sambuc   unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2079f4a2713aSLionel Sambuc       : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2080f4a2713aSLionel Sambuc   llvm::errs() << NumUninitAnalysisFunctions
2081f4a2713aSLionel Sambuc                << " functions analyzed for uninitialiazed variables\n"
2082f4a2713aSLionel Sambuc                << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
2083f4a2713aSLionel Sambuc                << "  " << AvgUninitVariablesPerFunction
2084f4a2713aSLionel Sambuc                << " average variables per function.\n"
2085f4a2713aSLionel Sambuc                << "  " << MaxUninitAnalysisVariablesPerFunction
2086f4a2713aSLionel Sambuc                << " max variables per function.\n"
2087f4a2713aSLionel Sambuc                << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
2088f4a2713aSLionel Sambuc                << "  " << AvgUninitBlockVisitsPerFunction
2089f4a2713aSLionel Sambuc                << " average block visits per function.\n"
2090f4a2713aSLionel Sambuc                << "  " << MaxUninitAnalysisBlockVisitsPerFunction
2091f4a2713aSLionel Sambuc                << " max block visits per function.\n";
2092f4a2713aSLionel Sambuc }
2093