AnalysisBasedWarnings.cpp revision b5cd1220dd650a358622241237aa595c5d675506
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/Sema/SemaInternal.h"
18#include "clang/Sema/ScopeInfo.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/StmtObjC.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/EvaluatedExprVisitor.h"
30#include "clang/AST/ParentMap.h"
31#include "clang/AST/StmtVisitor.h"
32#include "clang/AST/RecursiveASTVisitor.h"
33#include "clang/Analysis/AnalysisContext.h"
34#include "clang/Analysis/CFG.h"
35#include "clang/Analysis/Analyses/ReachableCode.h"
36#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
37#include "clang/Analysis/Analyses/ThreadSafety.h"
38#include "clang/Analysis/CFGStmtMap.h"
39#include "clang/Analysis/Analyses/UninitializedValues.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/BitVector.h"
42#include "llvm/ADT/FoldingSet.h"
43#include "llvm/ADT/ImmutableMap.h"
44#include "llvm/ADT/PostOrderIterator.h"
45#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/Support/Casting.h"
49#include <algorithm>
50#include <iterator>
51#include <vector>
52#include <deque>
53
54using namespace clang;
55
56//===----------------------------------------------------------------------===//
57// Unreachable code analysis.
58//===----------------------------------------------------------------------===//
59
60namespace {
61  class UnreachableCodeHandler : public reachable_code::Callback {
62    Sema &S;
63  public:
64    UnreachableCodeHandler(Sema &s) : S(s) {}
65
66    void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
67      S.Diag(L, diag::warn_unreachable) << R1 << R2;
68    }
69  };
70}
71
72/// CheckUnreachable - Check for unreachable code.
73static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
74  UnreachableCodeHandler UC(S);
75  reachable_code::FindUnreachableCode(AC, UC);
76}
77
78//===----------------------------------------------------------------------===//
79// Check for missing return value.
80//===----------------------------------------------------------------------===//
81
82enum ControlFlowKind {
83  UnknownFallThrough,
84  NeverFallThrough,
85  MaybeFallThrough,
86  AlwaysFallThrough,
87  NeverFallThroughOrReturn
88};
89
90/// CheckFallThrough - Check that we don't fall off the end of a
91/// Statement that should return a value.
92///
93/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
94/// MaybeFallThrough iff we might or might not fall off the end,
95/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
96/// return.  We assume NeverFallThrough iff we never fall off the end of the
97/// statement but we may return.  We assume that functions not marked noreturn
98/// will return.
99static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
100  CFG *cfg = AC.getCFG();
101  if (cfg == 0) return UnknownFallThrough;
102
103  // The CFG leaves in dead things, and we don't want the dead code paths to
104  // confuse us, so we mark all live things first.
105  llvm::BitVector live(cfg->getNumBlockIDs());
106  unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
107                                                          live);
108
109  bool AddEHEdges = AC.getAddEHEdges();
110  if (!AddEHEdges && count != cfg->getNumBlockIDs())
111    // When there are things remaining dead, and we didn't add EH edges
112    // from CallExprs to the catch clauses, we have to go back and
113    // mark them as live.
114    for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
115      CFGBlock &b = **I;
116      if (!live[b.getBlockID()]) {
117        if (b.pred_begin() == b.pred_end()) {
118          if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
119            // When not adding EH edges from calls, catch clauses
120            // can otherwise seem dead.  Avoid noting them as dead.
121            count += reachable_code::ScanReachableFromBlock(&b, live);
122          continue;
123        }
124      }
125    }
126
127  // Now we know what is live, we check the live precessors of the exit block
128  // and look for fall through paths, being careful to ignore normal returns,
129  // and exceptional paths.
130  bool HasLiveReturn = false;
131  bool HasFakeEdge = false;
132  bool HasPlainEdge = false;
133  bool HasAbnormalEdge = false;
134
135  // Ignore default cases that aren't likely to be reachable because all
136  // enums in a switch(X) have explicit case statements.
137  CFGBlock::FilterOptions FO;
138  FO.IgnoreDefaultsWithCoveredEnums = 1;
139
140  for (CFGBlock::filtered_pred_iterator
141	 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
142    const CFGBlock& B = **I;
143    if (!live[B.getBlockID()])
144      continue;
145
146    // Skip blocks which contain an element marked as no-return. They don't
147    // represent actually viable edges into the exit block, so mark them as
148    // abnormal.
149    if (B.hasNoReturnElement()) {
150      HasAbnormalEdge = true;
151      continue;
152    }
153
154    // Destructors can appear after the 'return' in the CFG.  This is
155    // normal.  We need to look pass the destructors for the return
156    // statement (if it exists).
157    CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
158
159    for ( ; ri != re ; ++ri)
160      if (isa<CFGStmt>(*ri))
161        break;
162
163    // No more CFGElements in the block?
164    if (ri == re) {
165      if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
166        HasAbnormalEdge = true;
167        continue;
168      }
169      // A labeled empty statement, or the entry block...
170      HasPlainEdge = true;
171      continue;
172    }
173
174    CFGStmt CS = cast<CFGStmt>(*ri);
175    const Stmt *S = CS.getStmt();
176    if (isa<ReturnStmt>(S)) {
177      HasLiveReturn = true;
178      continue;
179    }
180    if (isa<ObjCAtThrowStmt>(S)) {
181      HasFakeEdge = true;
182      continue;
183    }
184    if (isa<CXXThrowExpr>(S)) {
185      HasFakeEdge = true;
186      continue;
187    }
188    if (isa<MSAsmStmt>(S)) {
189      // TODO: Verify this is correct.
190      HasFakeEdge = true;
191      HasLiveReturn = true;
192      continue;
193    }
194    if (isa<CXXTryStmt>(S)) {
195      HasAbnormalEdge = true;
196      continue;
197    }
198    if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
199        == B.succ_end()) {
200      HasAbnormalEdge = true;
201      continue;
202    }
203
204    HasPlainEdge = true;
205  }
206  if (!HasPlainEdge) {
207    if (HasLiveReturn)
208      return NeverFallThrough;
209    return NeverFallThroughOrReturn;
210  }
211  if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
212    return MaybeFallThrough;
213  // This says AlwaysFallThrough for calls to functions that are not marked
214  // noreturn, that don't return.  If people would like this warning to be more
215  // accurate, such functions should be marked as noreturn.
216  return AlwaysFallThrough;
217}
218
219namespace {
220
221struct CheckFallThroughDiagnostics {
222  unsigned diag_MaybeFallThrough_HasNoReturn;
223  unsigned diag_MaybeFallThrough_ReturnsNonVoid;
224  unsigned diag_AlwaysFallThrough_HasNoReturn;
225  unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
226  unsigned diag_NeverFallThroughOrReturn;
227  enum { Function, Block, Lambda } funMode;
228  SourceLocation FuncLoc;
229
230  static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
231    CheckFallThroughDiagnostics D;
232    D.FuncLoc = Func->getLocation();
233    D.diag_MaybeFallThrough_HasNoReturn =
234      diag::warn_falloff_noreturn_function;
235    D.diag_MaybeFallThrough_ReturnsNonVoid =
236      diag::warn_maybe_falloff_nonvoid_function;
237    D.diag_AlwaysFallThrough_HasNoReturn =
238      diag::warn_falloff_noreturn_function;
239    D.diag_AlwaysFallThrough_ReturnsNonVoid =
240      diag::warn_falloff_nonvoid_function;
241
242    // Don't suggest that virtual functions be marked "noreturn", since they
243    // might be overridden by non-noreturn functions.
244    bool isVirtualMethod = false;
245    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
246      isVirtualMethod = Method->isVirtual();
247
248    // Don't suggest that template instantiations be marked "noreturn"
249    bool isTemplateInstantiation = false;
250    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
251      isTemplateInstantiation = Function->isTemplateInstantiation();
252
253    if (!isVirtualMethod && !isTemplateInstantiation)
254      D.diag_NeverFallThroughOrReturn =
255        diag::warn_suggest_noreturn_function;
256    else
257      D.diag_NeverFallThroughOrReturn = 0;
258
259    D.funMode = Function;
260    return D;
261  }
262
263  static CheckFallThroughDiagnostics MakeForBlock() {
264    CheckFallThroughDiagnostics D;
265    D.diag_MaybeFallThrough_HasNoReturn =
266      diag::err_noreturn_block_has_return_expr;
267    D.diag_MaybeFallThrough_ReturnsNonVoid =
268      diag::err_maybe_falloff_nonvoid_block;
269    D.diag_AlwaysFallThrough_HasNoReturn =
270      diag::err_noreturn_block_has_return_expr;
271    D.diag_AlwaysFallThrough_ReturnsNonVoid =
272      diag::err_falloff_nonvoid_block;
273    D.diag_NeverFallThroughOrReturn =
274      diag::warn_suggest_noreturn_block;
275    D.funMode = Block;
276    return D;
277  }
278
279  static CheckFallThroughDiagnostics MakeForLambda() {
280    CheckFallThroughDiagnostics D;
281    D.diag_MaybeFallThrough_HasNoReturn =
282      diag::err_noreturn_lambda_has_return_expr;
283    D.diag_MaybeFallThrough_ReturnsNonVoid =
284      diag::warn_maybe_falloff_nonvoid_lambda;
285    D.diag_AlwaysFallThrough_HasNoReturn =
286      diag::err_noreturn_lambda_has_return_expr;
287    D.diag_AlwaysFallThrough_ReturnsNonVoid =
288      diag::warn_falloff_nonvoid_lambda;
289    D.diag_NeverFallThroughOrReturn = 0;
290    D.funMode = Lambda;
291    return D;
292  }
293
294  bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
295                        bool HasNoReturn) const {
296    if (funMode == Function) {
297      return (ReturnsVoid ||
298              D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
299                                   FuncLoc) == DiagnosticsEngine::Ignored)
300        && (!HasNoReturn ||
301            D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
302                                 FuncLoc) == DiagnosticsEngine::Ignored)
303        && (!ReturnsVoid ||
304            D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
305              == DiagnosticsEngine::Ignored);
306    }
307
308    // For blocks / lambdas.
309    return ReturnsVoid && !HasNoReturn
310            && ((funMode == Lambda) ||
311                D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
312                  == DiagnosticsEngine::Ignored);
313  }
314};
315
316}
317
318/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319/// function that should return a value.  Check that we don't fall off the end
320/// of a noreturn function.  We assume that functions and blocks not marked
321/// noreturn will return.
322static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
323                                    const BlockExpr *blkExpr,
324                                    const CheckFallThroughDiagnostics& CD,
325                                    AnalysisDeclContext &AC) {
326
327  bool ReturnsVoid = false;
328  bool HasNoReturn = false;
329
330  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331    ReturnsVoid = FD->getResultType()->isVoidType();
332    HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
333       FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
334  }
335  else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
336    ReturnsVoid = MD->getResultType()->isVoidType();
337    HasNoReturn = MD->hasAttr<NoReturnAttr>();
338  }
339  else if (isa<BlockDecl>(D)) {
340    QualType BlockTy = blkExpr->getType();
341    if (const FunctionType *FT =
342          BlockTy->getPointeeType()->getAs<FunctionType>()) {
343      if (FT->getResultType()->isVoidType())
344        ReturnsVoid = true;
345      if (FT->getNoReturnAttr())
346        HasNoReturn = true;
347    }
348  }
349
350  DiagnosticsEngine &Diags = S.getDiagnostics();
351
352  // Short circuit for compilation speed.
353  if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
354      return;
355
356  // FIXME: Function try block
357  if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
358    switch (CheckFallThrough(AC)) {
359      case UnknownFallThrough:
360        break;
361
362      case MaybeFallThrough:
363        if (HasNoReturn)
364          S.Diag(Compound->getRBracLoc(),
365                 CD.diag_MaybeFallThrough_HasNoReturn);
366        else if (!ReturnsVoid)
367          S.Diag(Compound->getRBracLoc(),
368                 CD.diag_MaybeFallThrough_ReturnsNonVoid);
369        break;
370      case AlwaysFallThrough:
371        if (HasNoReturn)
372          S.Diag(Compound->getRBracLoc(),
373                 CD.diag_AlwaysFallThrough_HasNoReturn);
374        else if (!ReturnsVoid)
375          S.Diag(Compound->getRBracLoc(),
376                 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
377        break;
378      case NeverFallThroughOrReturn:
379        if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
380          if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
381            S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
382              << 0 << FD;
383          } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
384            S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
385              << 1 << MD;
386          } else {
387            S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
388          }
389        }
390        break;
391      case NeverFallThrough:
392        break;
393    }
394  }
395}
396
397//===----------------------------------------------------------------------===//
398// -Wuninitialized
399//===----------------------------------------------------------------------===//
400
401namespace {
402/// ContainsReference - A visitor class to search for references to
403/// a particular declaration (the needle) within any evaluated component of an
404/// expression (recursively).
405class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
406  bool FoundReference;
407  const DeclRefExpr *Needle;
408
409public:
410  ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
411    : EvaluatedExprVisitor<ContainsReference>(Context),
412      FoundReference(false), Needle(Needle) {}
413
414  void VisitExpr(Expr *E) {
415    // Stop evaluating if we already have a reference.
416    if (FoundReference)
417      return;
418
419    EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
420  }
421
422  void VisitDeclRefExpr(DeclRefExpr *E) {
423    if (E == Needle)
424      FoundReference = true;
425    else
426      EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
427  }
428
429  bool doesContainReference() const { return FoundReference; }
430};
431}
432
433static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
434  QualType VariableTy = VD->getType().getCanonicalType();
435  if (VariableTy->isBlockPointerType() &&
436      !VD->hasAttr<BlocksAttr>()) {
437    S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
438    << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
439    return true;
440  }
441
442  // Don't issue a fixit if there is already an initializer.
443  if (VD->getInit())
444    return false;
445
446  // Suggest possible initialization (if any).
447  std::string Init = S.getFixItZeroInitializerForType(VariableTy);
448  if (Init.empty())
449    return false;
450
451  // Don't suggest a fixit inside macros.
452  if (VD->getLocEnd().isMacroID())
453    return false;
454
455  SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
456
457  S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
458    << FixItHint::CreateInsertion(Loc, Init);
459  return true;
460}
461
462/// Create a fixit to remove an if-like statement, on the assumption that its
463/// condition is CondVal.
464static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
465                          const Stmt *Else, bool CondVal,
466                          FixItHint &Fixit1, FixItHint &Fixit2) {
467  if (CondVal) {
468    // If condition is always true, remove all but the 'then'.
469    Fixit1 = FixItHint::CreateRemoval(
470        CharSourceRange::getCharRange(If->getLocStart(),
471                                      Then->getLocStart()));
472    if (Else) {
473      SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
474          Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
475      Fixit2 = FixItHint::CreateRemoval(
476          SourceRange(ElseKwLoc, Else->getLocEnd()));
477    }
478  } else {
479    // If condition is always false, remove all but the 'else'.
480    if (Else)
481      Fixit1 = FixItHint::CreateRemoval(
482          CharSourceRange::getCharRange(If->getLocStart(),
483                                        Else->getLocStart()));
484    else
485      Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
486  }
487}
488
489/// DiagUninitUse -- Helper function to produce a diagnostic for an
490/// uninitialized use of a variable.
491static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
492                          bool IsCapturedByBlock) {
493  bool Diagnosed = false;
494
495  // Diagnose each branch which leads to a sometimes-uninitialized use.
496  for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
497       I != E; ++I) {
498    assert(Use.getKind() == UninitUse::Sometimes);
499
500    const Expr *User = Use.getUser();
501    const Stmt *Term = I->Terminator;
502
503    // Information used when building the diagnostic.
504    unsigned DiagKind;
505    StringRef Str;
506    SourceRange Range;
507
508    // FixIts to suppress the diagnosic by removing the dead condition.
509    // For all binary terminators, branch 0 is taken if the condition is true,
510    // and branch 1 is taken if the condition is false.
511    int RemoveDiagKind = -1;
512    const char *FixitStr =
513        S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
514                                  : (I->Output ? "1" : "0");
515    FixItHint Fixit1, Fixit2;
516
517    switch (Term->getStmtClass()) {
518    default:
519      // Don't know how to report this. Just fall back to 'may be used
520      // uninitialized'. This happens for range-based for, which the user
521      // can't explicitly fix.
522      // FIXME: This also happens if the first use of a variable is always
523      // uninitialized, eg "for (int n; n < 10; ++n)". We should report that
524      // with the 'is uninitialized' diagnostic.
525      continue;
526
527    // "condition is true / condition is false".
528    case Stmt::IfStmtClass: {
529      const IfStmt *IS = cast<IfStmt>(Term);
530      DiagKind = 0;
531      Str = "if";
532      Range = IS->getCond()->getSourceRange();
533      RemoveDiagKind = 0;
534      CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
535                    I->Output, Fixit1, Fixit2);
536      break;
537    }
538    case Stmt::ConditionalOperatorClass: {
539      const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
540      DiagKind = 0;
541      Str = "?:";
542      Range = CO->getCond()->getSourceRange();
543      RemoveDiagKind = 0;
544      CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
545                    I->Output, Fixit1, Fixit2);
546      break;
547    }
548    case Stmt::BinaryOperatorClass: {
549      const BinaryOperator *BO = cast<BinaryOperator>(Term);
550      if (!BO->isLogicalOp())
551        continue;
552      DiagKind = 0;
553      Str = BO->getOpcodeStr();
554      Range = BO->getLHS()->getSourceRange();
555      RemoveDiagKind = 0;
556      if ((BO->getOpcode() == BO_LAnd && I->Output) ||
557          (BO->getOpcode() == BO_LOr && !I->Output))
558        // true && y -> y, false || y -> y.
559        Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
560                                                      BO->getOperatorLoc()));
561      else
562        // false && y -> false, true || y -> true.
563        Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
564      break;
565    }
566
567    // "loop is entered / loop is exited".
568    case Stmt::WhileStmtClass:
569      DiagKind = 1;
570      Str = "while";
571      Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
572      RemoveDiagKind = 1;
573      Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
574      break;
575    case Stmt::ForStmtClass:
576      DiagKind = 1;
577      Str = "for";
578      Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
579      RemoveDiagKind = 1;
580      if (I->Output)
581        Fixit1 = FixItHint::CreateRemoval(Range);
582      else
583        Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
584      break;
585
586    // "condition is true / loop is exited".
587    case Stmt::DoStmtClass:
588      DiagKind = 2;
589      Str = "do";
590      Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
591      RemoveDiagKind = 1;
592      Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
593      break;
594
595    // "switch case is taken".
596    case Stmt::CaseStmtClass:
597      DiagKind = 3;
598      Str = "case";
599      Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
600      break;
601    case Stmt::DefaultStmtClass:
602      DiagKind = 3;
603      Str = "default";
604      Range = cast<DefaultStmt>(Term)->getDefaultLoc();
605      break;
606    }
607
608    S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
609      << VD->getDeclName() << IsCapturedByBlock << DiagKind
610      << Str << I->Output << Range;
611    S.Diag(User->getLocStart(), diag::note_uninit_var_use)
612      << IsCapturedByBlock << User->getSourceRange();
613    if (RemoveDiagKind != -1)
614      S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
615        << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
616
617    Diagnosed = true;
618  }
619
620  if (!Diagnosed)
621    S.Diag(Use.getUser()->getLocStart(),
622           Use.getKind() == UninitUse::Always ? diag::warn_uninit_var
623                                              : diag::warn_maybe_uninit_var)
624        << VD->getDeclName() << IsCapturedByBlock
625        << Use.getUser()->getSourceRange();
626}
627
628/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
629/// uninitialized variable. This manages the different forms of diagnostic
630/// emitted for particular types of uses. Returns true if the use was diagnosed
631/// as a warning. If a particular use is one we omit warnings for, returns
632/// false.
633static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
634                                     const UninitUse &Use,
635                                     bool alwaysReportSelfInit = false) {
636
637  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
638    // Inspect the initializer of the variable declaration which is
639    // being referenced prior to its initialization. We emit
640    // specialized diagnostics for self-initialization, and we
641    // specifically avoid warning about self references which take the
642    // form of:
643    //
644    //   int x = x;
645    //
646    // This is used to indicate to GCC that 'x' is intentionally left
647    // uninitialized. Proven code paths which access 'x' in
648    // an uninitialized state after this will still warn.
649    if (const Expr *Initializer = VD->getInit()) {
650      if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
651        return false;
652
653      ContainsReference CR(S.Context, DRE);
654      CR.Visit(const_cast<Expr*>(Initializer));
655      if (CR.doesContainReference()) {
656        S.Diag(DRE->getLocStart(),
657               diag::warn_uninit_self_reference_in_init)
658          << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
659        return true;
660      }
661    }
662
663    DiagUninitUse(S, VD, Use, false);
664  } else {
665    const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
666    if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
667      S.Diag(BE->getLocStart(),
668             diag::warn_uninit_byref_blockvar_captured_by_block)
669        << VD->getDeclName();
670    else
671      DiagUninitUse(S, VD, Use, true);
672  }
673
674  // Report where the variable was declared when the use wasn't within
675  // the initializer of that declaration & we didn't already suggest
676  // an initialization fixit.
677  if (!SuggestInitializationFixit(S, VD))
678    S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
679      << VD->getDeclName();
680
681  return true;
682}
683
684namespace {
685  class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
686  public:
687    FallthroughMapper(Sema &S)
688      : FoundSwitchStatements(false),
689        S(S) {
690    }
691
692    bool foundSwitchStatements() const { return FoundSwitchStatements; }
693
694    void markFallthroughVisited(const AttributedStmt *Stmt) {
695      bool Found = FallthroughStmts.erase(Stmt);
696      assert(Found);
697      (void)Found;
698    }
699
700    typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
701
702    const AttrStmts &getFallthroughStmts() const {
703      return FallthroughStmts;
704    }
705
706    bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
707      int UnannotatedCnt = 0;
708      AnnotatedCnt = 0;
709
710      std::deque<const CFGBlock*> BlockQueue;
711
712      std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
713
714      while (!BlockQueue.empty()) {
715        const CFGBlock *P = BlockQueue.front();
716        BlockQueue.pop_front();
717
718        const Stmt *Term = P->getTerminator();
719        if (Term && isa<SwitchStmt>(Term))
720          continue; // Switch statement, good.
721
722        const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
723        if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
724          continue; // Previous case label has no statements, good.
725
726        if (P->pred_begin() == P->pred_end()) {  // The block is unreachable.
727          // This only catches trivially unreachable blocks.
728          for (CFGBlock::const_iterator ElIt = P->begin(), ElEnd = P->end();
729               ElIt != ElEnd; ++ElIt) {
730            if (const CFGStmt *CS = ElIt->getAs<CFGStmt>()){
731              if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
732                S.Diag(AS->getLocStart(),
733                       diag::warn_fallthrough_attr_unreachable);
734                markFallthroughVisited(AS);
735                ++AnnotatedCnt;
736              }
737              // Don't care about other unreachable statements.
738            }
739          }
740          // If there are no unreachable statements, this may be a special
741          // case in CFG:
742          // case X: {
743          //    A a;  // A has a destructor.
744          //    break;
745          // }
746          // // <<<< This place is represented by a 'hanging' CFG block.
747          // case Y:
748          continue;
749        }
750
751        const Stmt *LastStmt = getLastStmt(*P);
752        if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
753          markFallthroughVisited(AS);
754          ++AnnotatedCnt;
755          continue; // Fallthrough annotation, good.
756        }
757
758        if (!LastStmt) { // This block contains no executable statements.
759          // Traverse its predecessors.
760          std::copy(P->pred_begin(), P->pred_end(),
761                    std::back_inserter(BlockQueue));
762          continue;
763        }
764
765        ++UnannotatedCnt;
766      }
767      return !!UnannotatedCnt;
768    }
769
770    // RecursiveASTVisitor setup.
771    bool shouldWalkTypesOfTypeLocs() const { return false; }
772
773    bool VisitAttributedStmt(AttributedStmt *S) {
774      if (asFallThroughAttr(S))
775        FallthroughStmts.insert(S);
776      return true;
777    }
778
779    bool VisitSwitchStmt(SwitchStmt *S) {
780      FoundSwitchStatements = true;
781      return true;
782    }
783
784  private:
785
786    static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
787      if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
788        if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
789          return AS;
790      }
791      return 0;
792    }
793
794    static const Stmt *getLastStmt(const CFGBlock &B) {
795      if (const Stmt *Term = B.getTerminator())
796        return Term;
797      for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
798                                            ElemEnd = B.rend();
799                                            ElemIt != ElemEnd; ++ElemIt) {
800        if (const CFGStmt *CS = ElemIt->getAs<CFGStmt>())
801          return CS->getStmt();
802      }
803      // Workaround to detect a statement thrown out by CFGBuilder:
804      //   case X: {} case Y:
805      //   case X: ; case Y:
806      if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
807        if (!isa<SwitchCase>(SW->getSubStmt()))
808          return SW->getSubStmt();
809
810      return 0;
811    }
812
813    bool FoundSwitchStatements;
814    AttrStmts FallthroughStmts;
815    Sema &S;
816  };
817}
818
819static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
820                                            bool PerFunction) {
821  FallthroughMapper FM(S);
822  FM.TraverseStmt(AC.getBody());
823
824  if (!FM.foundSwitchStatements())
825    return;
826
827  if (PerFunction && FM.getFallthroughStmts().empty())
828    return;
829
830  CFG *Cfg = AC.getCFG();
831
832  if (!Cfg)
833    return;
834
835  int AnnotatedCnt;
836
837  for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
838    const CFGBlock &B = **I;
839    const Stmt *Label = B.getLabel();
840
841    if (!Label || !isa<SwitchCase>(Label))
842      continue;
843
844    if (!FM.checkFallThroughIntoBlock(B, AnnotatedCnt))
845      continue;
846
847    S.Diag(Label->getLocStart(),
848        PerFunction ? diag::warn_unannotated_fallthrough_per_function
849                    : diag::warn_unannotated_fallthrough);
850
851    if (!AnnotatedCnt) {
852      SourceLocation L = Label->getLocStart();
853      if (L.isMacroID())
854        continue;
855      if (S.getLangOpts().CPlusPlus0x) {
856        const Stmt *Term = B.getTerminator();
857        if (!(B.empty() && Term && isa<BreakStmt>(Term))) {
858          Preprocessor &PP = S.getPreprocessor();
859          TokenValue Tokens[] = {
860            tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
861            tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
862            tok::r_square, tok::r_square
863          };
864          StringRef AnnotationSpelling = "[[clang::fallthrough]]";
865          StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
866          if (!MacroName.empty())
867            AnnotationSpelling = MacroName;
868          SmallString<64> TextToInsert(AnnotationSpelling);
869          TextToInsert += "; ";
870          S.Diag(L, diag::note_insert_fallthrough_fixit) <<
871              AnnotationSpelling <<
872              FixItHint::CreateInsertion(L, TextToInsert);
873        }
874      }
875      S.Diag(L, diag::note_insert_break_fixit) <<
876        FixItHint::CreateInsertion(L, "break; ");
877    }
878  }
879
880  const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
881  for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
882                                                    E = Fallthroughs.end();
883                                                    I != E; ++I) {
884    S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
885  }
886
887}
888
889namespace {
890typedef std::pair<const Stmt *,
891                  sema::FunctionScopeInfo::WeakObjectUseMap::const_iterator>
892        StmtUsesPair;
893
894class StmtUseSorter {
895  const SourceManager &SM;
896
897public:
898  explicit StmtUseSorter(const SourceManager &SM) : SM(SM) { }
899
900  bool operator()(const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
901    return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
902                                        RHS.first->getLocStart());
903  }
904};
905}
906
907static bool isInLoop(const ParentMap &PM, const Stmt *S) {
908  assert(S);
909
910  do {
911    switch (S->getStmtClass()) {
912    case Stmt::DoStmtClass:
913    case Stmt::ForStmtClass:
914    case Stmt::WhileStmtClass:
915    case Stmt::CXXForRangeStmtClass:
916    case Stmt::ObjCForCollectionStmtClass:
917      return true;
918    default:
919      break;
920    }
921  } while ((S = PM.getParent(S)));
922
923  return false;
924}
925
926
927static void diagnoseRepeatedUseOfWeak(Sema &S,
928                                      const sema::FunctionScopeInfo *CurFn,
929                                      const Decl *D,
930                                      const ParentMap &PM) {
931  typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
932  typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
933  typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
934
935  const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
936
937  // Extract all weak objects that are referenced more than once.
938  SmallVector<StmtUsesPair, 8> UsesByStmt;
939  for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
940       I != E; ++I) {
941    const WeakUseVector &Uses = I->second;
942
943    // Find the first read of the weak object.
944    WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
945    for ( ; UI != UE; ++UI) {
946      if (UI->isUnsafe())
947        break;
948    }
949
950    // If there were only writes to this object, don't warn.
951    if (UI == UE)
952      continue;
953
954    // If there was only one read, followed by any number of writes, and the
955    // read is not within a loop, don't warn.
956    if (UI == Uses.begin()) {
957      WeakUseVector::const_iterator UI2 = UI;
958      for (++UI2; UI2 != UE; ++UI2)
959        if (UI2->isUnsafe())
960          break;
961
962      if (UI2 == UE)
963        if (!isInLoop(PM, UI->getUseExpr()))
964          continue;
965    }
966
967    UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
968  }
969
970  if (UsesByStmt.empty())
971    return;
972
973  // Sort by first use so that we emit the warnings in a deterministic order.
974  std::sort(UsesByStmt.begin(), UsesByStmt.end(),
975            StmtUseSorter(S.getSourceManager()));
976
977  // Classify the current code body for better warning text.
978  // This enum should stay in sync with the cases in
979  // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
980  // FIXME: Should we use a common classification enum and the same set of
981  // possibilities all throughout Sema?
982  enum {
983    Function,
984    Method,
985    Block,
986    Lambda
987  } FunctionKind;
988
989  if (isa<sema::BlockScopeInfo>(CurFn))
990    FunctionKind = Block;
991  else if (isa<sema::LambdaScopeInfo>(CurFn))
992    FunctionKind = Lambda;
993  else if (isa<ObjCMethodDecl>(D))
994    FunctionKind = Method;
995  else
996    FunctionKind = Function;
997
998  // Iterate through the sorted problems and emit warnings for each.
999  for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1000                                                     E = UsesByStmt.end();
1001       I != E; ++I) {
1002    const Stmt *FirstRead = I->first;
1003    const WeakObjectProfileTy &Key = I->second->first;
1004    const WeakUseVector &Uses = I->second->second;
1005
1006    // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1007    // may not contain enough information to determine that these are different
1008    // properties. We can only be 100% sure of a repeated use in certain cases,
1009    // and we adjust the diagnostic kind accordingly so that the less certain
1010    // case can be turned off if it is too noisy.
1011    unsigned DiagKind;
1012    if (Key.isExactProfile())
1013      DiagKind = diag::warn_arc_repeated_use_of_weak;
1014    else
1015      DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1016
1017    // Classify the weak object being accessed for better warning text.
1018    // This enum should stay in sync with the cases in
1019    // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1020    enum {
1021      Variable,
1022      Property,
1023      ImplicitProperty,
1024      Ivar
1025    } ObjectKind;
1026
1027    const NamedDecl *D = Key.getProperty();
1028    if (isa<VarDecl>(D))
1029      ObjectKind = Variable;
1030    else if (isa<ObjCPropertyDecl>(D))
1031      ObjectKind = Property;
1032    else if (isa<ObjCMethodDecl>(D))
1033      ObjectKind = ImplicitProperty;
1034    else if (isa<ObjCIvarDecl>(D))
1035      ObjectKind = Ivar;
1036    else
1037      llvm_unreachable("Unexpected weak object kind!");
1038
1039    // Show the first time the object was read.
1040    S.Diag(FirstRead->getLocStart(), DiagKind)
1041      << ObjectKind << D << FunctionKind
1042      << FirstRead->getSourceRange();
1043
1044    // Print all the other accesses as notes.
1045    for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1046         UI != UE; ++UI) {
1047      if (UI->getUseExpr() == FirstRead)
1048        continue;
1049      S.Diag(UI->getUseExpr()->getLocStart(),
1050             diag::note_arc_weak_also_accessed_here)
1051        << UI->getUseExpr()->getSourceRange();
1052    }
1053  }
1054}
1055
1056
1057namespace {
1058struct SLocSort {
1059  bool operator()(const UninitUse &a, const UninitUse &b) {
1060    // Prefer a more confident report over a less confident one.
1061    if (a.getKind() != b.getKind())
1062      return a.getKind() > b.getKind();
1063    SourceLocation aLoc = a.getUser()->getLocStart();
1064    SourceLocation bLoc = b.getUser()->getLocStart();
1065    return aLoc.getRawEncoding() < bLoc.getRawEncoding();
1066  }
1067};
1068
1069class UninitValsDiagReporter : public UninitVariablesHandler {
1070  Sema &S;
1071  typedef SmallVector<UninitUse, 2> UsesVec;
1072  typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
1073  UsesMap *uses;
1074
1075public:
1076  UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1077  ~UninitValsDiagReporter() {
1078    flushDiagnostics();
1079  }
1080
1081  std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
1082    if (!uses)
1083      uses = new UsesMap();
1084
1085    UsesMap::mapped_type &V = (*uses)[vd];
1086    UsesVec *&vec = V.first;
1087    if (!vec)
1088      vec = new UsesVec();
1089
1090    return V;
1091  }
1092
1093  void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) {
1094    getUses(vd).first->push_back(use);
1095  }
1096
1097  void handleSelfInit(const VarDecl *vd) {
1098    getUses(vd).second = true;
1099  }
1100
1101  void flushDiagnostics() {
1102    if (!uses)
1103      return;
1104
1105    // FIXME: This iteration order, and thus the resulting diagnostic order,
1106    //        is nondeterministic.
1107    for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1108      const VarDecl *vd = i->first;
1109      const UsesMap::mapped_type &V = i->second;
1110
1111      UsesVec *vec = V.first;
1112      bool hasSelfInit = V.second;
1113
1114      // Specially handle the case where we have uses of an uninitialized
1115      // variable, but the root cause is an idiomatic self-init.  We want
1116      // to report the diagnostic at the self-init since that is the root cause.
1117      if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1118        DiagnoseUninitializedUse(S, vd,
1119                                 UninitUse(vd->getInit()->IgnoreParenCasts(),
1120                                           /* isAlwaysUninit */ true),
1121                                 /* alwaysReportSelfInit */ true);
1122      else {
1123        // Sort the uses by their SourceLocations.  While not strictly
1124        // guaranteed to produce them in line/column order, this will provide
1125        // a stable ordering.
1126        std::sort(vec->begin(), vec->end(), SLocSort());
1127
1128        for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1129             ++vi) {
1130          // If we have self-init, downgrade all uses to 'may be uninitialized'.
1131          UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1132
1133          if (DiagnoseUninitializedUse(S, vd, Use))
1134            // Skip further diagnostics for this variable. We try to warn only
1135            // on the first point at which a variable is used uninitialized.
1136            break;
1137        }
1138      }
1139
1140      // Release the uses vector.
1141      delete vec;
1142    }
1143    delete uses;
1144  }
1145
1146private:
1147  static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1148  for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
1149    if (i->getKind() == UninitUse::Always) {
1150      return true;
1151    }
1152  }
1153  return false;
1154}
1155};
1156}
1157
1158
1159//===----------------------------------------------------------------------===//
1160// -Wthread-safety
1161//===----------------------------------------------------------------------===//
1162namespace clang {
1163namespace thread_safety {
1164typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1165typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1166typedef std::list<DelayedDiag> DiagList;
1167
1168struct SortDiagBySourceLocation {
1169  SourceManager &SM;
1170  SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1171
1172  bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1173    // Although this call will be slow, this is only called when outputting
1174    // multiple warnings.
1175    return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
1176  }
1177};
1178
1179namespace {
1180class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1181  Sema &S;
1182  DiagList Warnings;
1183  SourceLocation FunLocation, FunEndLocation;
1184
1185  // Helper functions
1186  void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
1187    // Gracefully handle rare cases when the analysis can't get a more
1188    // precise source location.
1189    if (!Loc.isValid())
1190      Loc = FunLocation;
1191    PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
1192    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1193  }
1194
1195 public:
1196  ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1197    : S(S), FunLocation(FL), FunEndLocation(FEL) {}
1198
1199  /// \brief Emit all buffered diagnostics in order of sourcelocation.
1200  /// We need to output diagnostics produced while iterating through
1201  /// the lockset in deterministic order, so this function orders diagnostics
1202  /// and outputs them.
1203  void emitDiagnostics() {
1204    Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1205    for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1206         I != E; ++I) {
1207      S.Diag(I->first.first, I->first.second);
1208      const OptionalNotes &Notes = I->second;
1209      for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1210        S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1211    }
1212  }
1213
1214  void handleInvalidLockExp(SourceLocation Loc) {
1215    PartialDiagnosticAt Warning(Loc,
1216                                S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
1217    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1218  }
1219  void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
1220    warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
1221  }
1222
1223  void handleDoubleLock(Name LockName, SourceLocation Loc) {
1224    warnLockMismatch(diag::warn_double_lock, LockName, Loc);
1225  }
1226
1227  void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
1228                                 SourceLocation LocEndOfScope,
1229                                 LockErrorKind LEK){
1230    unsigned DiagID = 0;
1231    switch (LEK) {
1232      case LEK_LockedSomePredecessors:
1233        DiagID = diag::warn_lock_some_predecessors;
1234        break;
1235      case LEK_LockedSomeLoopIterations:
1236        DiagID = diag::warn_expecting_lock_held_on_loop;
1237        break;
1238      case LEK_LockedAtEndOfFunction:
1239        DiagID = diag::warn_no_unlock;
1240        break;
1241      case LEK_NotLockedAtEndOfFunction:
1242        DiagID = diag::warn_expecting_locked;
1243        break;
1244    }
1245    if (LocEndOfScope.isInvalid())
1246      LocEndOfScope = FunEndLocation;
1247
1248    PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
1249    PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
1250    Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1251  }
1252
1253
1254  void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
1255                                SourceLocation Loc2) {
1256    PartialDiagnosticAt Warning(
1257      Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
1258    PartialDiagnosticAt Note(
1259      Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
1260    Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1261  }
1262
1263  void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
1264                         AccessKind AK, SourceLocation Loc) {
1265    assert((POK == POK_VarAccess || POK == POK_VarDereference)
1266             && "Only works for variables");
1267    unsigned DiagID = POK == POK_VarAccess?
1268                        diag::warn_variable_requires_any_lock:
1269                        diag::warn_var_deref_requires_any_lock;
1270    PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1271      << D->getNameAsString() << getLockKindFromAccessKind(AK));
1272    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1273  }
1274
1275  void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
1276                          Name LockName, LockKind LK, SourceLocation Loc,
1277                          Name *PossibleMatch) {
1278    unsigned DiagID = 0;
1279    if (PossibleMatch) {
1280      switch (POK) {
1281        case POK_VarAccess:
1282          DiagID = diag::warn_variable_requires_lock_precise;
1283          break;
1284        case POK_VarDereference:
1285          DiagID = diag::warn_var_deref_requires_lock_precise;
1286          break;
1287        case POK_FunctionCall:
1288          DiagID = diag::warn_fun_requires_lock_precise;
1289          break;
1290      }
1291      PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1292        << D->getNameAsString() << LockName << LK);
1293      PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
1294                               << *PossibleMatch);
1295      Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1296    } else {
1297      switch (POK) {
1298        case POK_VarAccess:
1299          DiagID = diag::warn_variable_requires_lock;
1300          break;
1301        case POK_VarDereference:
1302          DiagID = diag::warn_var_deref_requires_lock;
1303          break;
1304        case POK_FunctionCall:
1305          DiagID = diag::warn_fun_requires_lock;
1306          break;
1307      }
1308      PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
1309        << D->getNameAsString() << LockName << LK);
1310      Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1311    }
1312  }
1313
1314  void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
1315    PartialDiagnosticAt Warning(Loc,
1316      S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
1317    Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1318  }
1319};
1320}
1321}
1322}
1323
1324//===----------------------------------------------------------------------===//
1325// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1326//  warnings on a function, method, or block.
1327//===----------------------------------------------------------------------===//
1328
1329clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1330  enableCheckFallThrough = 1;
1331  enableCheckUnreachable = 0;
1332  enableThreadSafetyAnalysis = 0;
1333}
1334
1335clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1336  : S(s),
1337    NumFunctionsAnalyzed(0),
1338    NumFunctionsWithBadCFGs(0),
1339    NumCFGBlocks(0),
1340    MaxCFGBlocksPerFunction(0),
1341    NumUninitAnalysisFunctions(0),
1342    NumUninitAnalysisVariables(0),
1343    MaxUninitAnalysisVariablesPerFunction(0),
1344    NumUninitAnalysisBlockVisits(0),
1345    MaxUninitAnalysisBlockVisitsPerFunction(0) {
1346  DiagnosticsEngine &D = S.getDiagnostics();
1347  DefaultPolicy.enableCheckUnreachable = (unsigned)
1348    (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1349        DiagnosticsEngine::Ignored);
1350  DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1351    (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1352     DiagnosticsEngine::Ignored);
1353
1354}
1355
1356static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
1357  for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1358       i = fscope->PossiblyUnreachableDiags.begin(),
1359       e = fscope->PossiblyUnreachableDiags.end();
1360       i != e; ++i) {
1361    const sema::PossiblyUnreachableDiag &D = *i;
1362    S.Diag(D.Loc, D.PD);
1363  }
1364}
1365
1366void clang::sema::
1367AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
1368                                     sema::FunctionScopeInfo *fscope,
1369                                     const Decl *D, const BlockExpr *blkExpr) {
1370
1371  // We avoid doing analysis-based warnings when there are errors for
1372  // two reasons:
1373  // (1) The CFGs often can't be constructed (if the body is invalid), so
1374  //     don't bother trying.
1375  // (2) The code already has problems; running the analysis just takes more
1376  //     time.
1377  DiagnosticsEngine &Diags = S.getDiagnostics();
1378
1379  // Do not do any analysis for declarations in system headers if we are
1380  // going to just ignore them.
1381  if (Diags.getSuppressSystemWarnings() &&
1382      S.SourceMgr.isInSystemHeader(D->getLocation()))
1383    return;
1384
1385  // For code in dependent contexts, we'll do this at instantiation time.
1386  if (cast<DeclContext>(D)->isDependentContext())
1387    return;
1388
1389  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1390    // Flush out any possibly unreachable diagnostics.
1391    flushDiagnostics(S, fscope);
1392    return;
1393  }
1394
1395  const Stmt *Body = D->getBody();
1396  assert(Body);
1397
1398  AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
1399
1400  // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1401  // explosion for destrutors that can result and the compile time hit.
1402  AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1403  AC.getCFGBuildOptions().AddEHEdges = false;
1404  AC.getCFGBuildOptions().AddInitializers = true;
1405  AC.getCFGBuildOptions().AddImplicitDtors = true;
1406  AC.getCFGBuildOptions().AddTemporaryDtors = true;
1407
1408  // Force that certain expressions appear as CFGElements in the CFG.  This
1409  // is used to speed up various analyses.
1410  // FIXME: This isn't the right factoring.  This is here for initial
1411  // prototyping, but we need a way for analyses to say what expressions they
1412  // expect to always be CFGElements and then fill in the BuildOptions
1413  // appropriately.  This is essentially a layering violation.
1414  if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
1415    // Unreachable code analysis and thread safety require a linearized CFG.
1416    AC.getCFGBuildOptions().setAllAlwaysAdd();
1417  }
1418  else {
1419    AC.getCFGBuildOptions()
1420      .setAlwaysAdd(Stmt::BinaryOperatorClass)
1421      .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
1422      .setAlwaysAdd(Stmt::BlockExprClass)
1423      .setAlwaysAdd(Stmt::CStyleCastExprClass)
1424      .setAlwaysAdd(Stmt::DeclRefExprClass)
1425      .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1426      .setAlwaysAdd(Stmt::UnaryOperatorClass)
1427      .setAlwaysAdd(Stmt::AttributedStmtClass);
1428  }
1429
1430  // Construct the analysis context with the specified CFG build options.
1431
1432  // Emit delayed diagnostics.
1433  if (!fscope->PossiblyUnreachableDiags.empty()) {
1434    bool analyzed = false;
1435
1436    // Register the expressions with the CFGBuilder.
1437    for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1438         i = fscope->PossiblyUnreachableDiags.begin(),
1439         e = fscope->PossiblyUnreachableDiags.end();
1440         i != e; ++i) {
1441      if (const Stmt *stmt = i->stmt)
1442        AC.registerForcedBlockExpression(stmt);
1443    }
1444
1445    if (AC.getCFG()) {
1446      analyzed = true;
1447      for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
1448            i = fscope->PossiblyUnreachableDiags.begin(),
1449            e = fscope->PossiblyUnreachableDiags.end();
1450            i != e; ++i)
1451      {
1452        const sema::PossiblyUnreachableDiag &D = *i;
1453        bool processed = false;
1454        if (const Stmt *stmt = i->stmt) {
1455          const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1456          CFGReverseBlockReachabilityAnalysis *cra =
1457              AC.getCFGReachablityAnalysis();
1458          // FIXME: We should be able to assert that block is non-null, but
1459          // the CFG analysis can skip potentially-evaluated expressions in
1460          // edge cases; see test/Sema/vla-2.c.
1461          if (block && cra) {
1462            // Can this block be reached from the entrance?
1463            if (cra->isReachable(&AC.getCFG()->getEntry(), block))
1464              S.Diag(D.Loc, D.PD);
1465            processed = true;
1466          }
1467        }
1468        if (!processed) {
1469          // Emit the warning anyway if we cannot map to a basic block.
1470          S.Diag(D.Loc, D.PD);
1471        }
1472      }
1473    }
1474
1475    if (!analyzed)
1476      flushDiagnostics(S, fscope);
1477  }
1478
1479
1480  // Warning: check missing 'return'
1481  if (P.enableCheckFallThrough) {
1482    const CheckFallThroughDiagnostics &CD =
1483      (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1484       : (isa<CXXMethodDecl>(D) &&
1485          cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1486          cast<CXXMethodDecl>(D)->getParent()->isLambda())
1487            ? CheckFallThroughDiagnostics::MakeForLambda()
1488            : CheckFallThroughDiagnostics::MakeForFunction(D));
1489    CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
1490  }
1491
1492  // Warning: check for unreachable code
1493  if (P.enableCheckUnreachable) {
1494    // Only check for unreachable code on non-template instantiations.
1495    // Different template instantiations can effectively change the control-flow
1496    // and it is very difficult to prove that a snippet of code in a template
1497    // is unreachable for all instantiations.
1498    bool isTemplateInstantiation = false;
1499    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1500      isTemplateInstantiation = Function->isTemplateInstantiation();
1501    if (!isTemplateInstantiation)
1502      CheckUnreachable(S, AC);
1503  }
1504
1505  // Check for thread safety violations
1506  if (P.enableThreadSafetyAnalysis) {
1507    SourceLocation FL = AC.getDecl()->getLocation();
1508    SourceLocation FEL = AC.getDecl()->getLocEnd();
1509    thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
1510    thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1511    Reporter.emitDiagnostics();
1512  }
1513
1514  if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
1515      != DiagnosticsEngine::Ignored ||
1516      Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1517      != DiagnosticsEngine::Ignored ||
1518      Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
1519      != DiagnosticsEngine::Ignored) {
1520    if (CFG *cfg = AC.getCFG()) {
1521      UninitValsDiagReporter reporter(S);
1522      UninitVariablesAnalysisStats stats;
1523      std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
1524      runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
1525                                        reporter, stats);
1526
1527      if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1528        ++NumUninitAnalysisFunctions;
1529        NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1530        NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1531        MaxUninitAnalysisVariablesPerFunction =
1532            std::max(MaxUninitAnalysisVariablesPerFunction,
1533                     stats.NumVariablesAnalyzed);
1534        MaxUninitAnalysisBlockVisitsPerFunction =
1535            std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1536                     stats.NumBlockVisits);
1537      }
1538    }
1539  }
1540
1541  bool FallThroughDiagFull =
1542      Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1543                               D->getLocStart()) != DiagnosticsEngine::Ignored;
1544  bool FallThroughDiagPerFunction =
1545      Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
1546                               D->getLocStart()) != DiagnosticsEngine::Ignored;
1547  if (FallThroughDiagFull || FallThroughDiagPerFunction) {
1548    DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
1549  }
1550
1551  if (S.getLangOpts().ObjCARCWeak &&
1552      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1553                               D->getLocStart()) != DiagnosticsEngine::Ignored)
1554    diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
1555
1556  // Collect statistics about the CFG if it was built.
1557  if (S.CollectStats && AC.isCFGBuilt()) {
1558    ++NumFunctionsAnalyzed;
1559    if (CFG *cfg = AC.getCFG()) {
1560      // If we successfully built a CFG for this context, record some more
1561      // detail information about it.
1562      NumCFGBlocks += cfg->getNumBlockIDs();
1563      MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
1564                                         cfg->getNumBlockIDs());
1565    } else {
1566      ++NumFunctionsWithBadCFGs;
1567    }
1568  }
1569}
1570
1571void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1572  llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1573
1574  unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1575  unsigned AvgCFGBlocksPerFunction =
1576      !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1577  llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1578               << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1579               << "  " << NumCFGBlocks << " CFG blocks built.\n"
1580               << "  " << AvgCFGBlocksPerFunction
1581               << " average CFG blocks per function.\n"
1582               << "  " << MaxCFGBlocksPerFunction
1583               << " max CFG blocks per function.\n";
1584
1585  unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1586      : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1587  unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1588      : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1589  llvm::errs() << NumUninitAnalysisFunctions
1590               << " functions analyzed for uninitialiazed variables\n"
1591               << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
1592               << "  " << AvgUninitVariablesPerFunction
1593               << " average variables per function.\n"
1594               << "  " << MaxUninitAnalysisVariablesPerFunction
1595               << " max variables per function.\n"
1596               << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
1597               << "  " << AvgUninitBlockVisitsPerFunction
1598               << " average block visits per function.\n"
1599               << "  " << MaxUninitAnalysisBlockVisitsPerFunction
1600               << " max block visits per function.\n";
1601}
1602