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