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