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