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