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