1//=== AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines analysis_warnings::[Policy,Executor].
10// Together they are used by Sema to issue warnings based on inexpensive
11// static analysis algorithms in libAnalysis.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/AnalysisBasedWarnings.h"
16#include "SemaLifetimeSafety.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DynamicRecursiveASTVisitor.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/OperationKinds.h"
27#include "clang/AST/ParentMap.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtVisitor.h"
31#include "clang/AST/Type.h"
32#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
33#include "clang/Analysis/Analyses/CalledOnceCheck.h"
34#include "clang/Analysis/Analyses/Consumed.h"
35#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h"
36#include "clang/Analysis/Analyses/ReachableCode.h"
37#include "clang/Analysis/Analyses/ThreadSafety.h"
38#include "clang/Analysis/Analyses/UninitializedValues.h"
39#include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
40#include "clang/Analysis/AnalysisDeclContext.h"
41#include "clang/Analysis/CFG.h"
42#include "clang/Analysis/CallGraph.h"
43#include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
44#include "clang/Basic/Diagnostic.h"
45#include "clang/Basic/DiagnosticSema.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Lex/Preprocessor.h"
49#include "clang/Sema/ScopeInfo.h"
50#include "clang/Sema/SemaInternal.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/BitVector.h"
53#include "llvm/ADT/DenseMap.h"
54#include "llvm/ADT/MapVector.h"
55#include "llvm/ADT/PostOrderIterator.h"
56#include "llvm/ADT/STLFunctionalExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/TimeProfiler.h"
62#include <algorithm>
63#include <deque>
64#include <iterator>
65#include <optional>
66
67using namespace clang;
68
69//===----------------------------------------------------------------------===//
70// Unreachable code analysis.
71//===----------------------------------------------------------------------===//
72
73namespace {
74 class UnreachableCodeHandler : public reachable_code::Callback {
75 Sema &S;
76 SourceRange PreviousSilenceableCondVal;
77
78 public:
79 UnreachableCodeHandler(Sema &s) : S(s) {}
80
81 void HandleUnreachable(reachable_code::UnreachableKind UK, SourceLocation L,
82 SourceRange SilenceableCondVal, SourceRange R1,
83 SourceRange R2, bool HasFallThroughAttr) override {
84 // If the diagnosed code is `[[fallthrough]];` and
85 // `-Wunreachable-code-fallthrough` is enabled, suppress `code will never
86 // be executed` warning to avoid generating diagnostic twice
87 if (HasFallThroughAttr &&
88 !S.getDiagnostics().isIgnored(DiagID: diag::warn_unreachable_fallthrough_attr,
89 Loc: SourceLocation()))
90 return;
91
92 // Avoid reporting multiple unreachable code diagnostics that are
93 // triggered by the same conditional value.
94 if (PreviousSilenceableCondVal.isValid() &&
95 SilenceableCondVal.isValid() &&
96 PreviousSilenceableCondVal == SilenceableCondVal)
97 return;
98 PreviousSilenceableCondVal = SilenceableCondVal;
99
100 unsigned diag = diag::warn_unreachable;
101 switch (UK) {
102 case reachable_code::UK_Break:
103 diag = diag::warn_unreachable_break;
104 break;
105 case reachable_code::UK_Return:
106 diag = diag::warn_unreachable_return;
107 break;
108 case reachable_code::UK_Loop_Increment:
109 diag = diag::warn_unreachable_loop_increment;
110 break;
111 case reachable_code::UK_Other:
112 break;
113 }
114
115 S.Diag(Loc: L, DiagID: diag) << R1 << R2;
116
117 SourceLocation Open = SilenceableCondVal.getBegin();
118 if (Open.isValid()) {
119 SourceLocation Close = SilenceableCondVal.getEnd();
120 Close = S.getLocForEndOfToken(Loc: Close);
121 if (Close.isValid()) {
122 S.Diag(Loc: Open, DiagID: diag::note_unreachable_silence)
123 << FixItHint::CreateInsertion(InsertionLoc: Open, Code: "/* DISABLES CODE */ (")
124 << FixItHint::CreateInsertion(InsertionLoc: Close, Code: ")");
125 }
126 }
127 }
128 };
129} // anonymous namespace
130
131/// CheckUnreachable - Check for unreachable code.
132static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
133 // As a heuristic prune all diagnostics not in the main file. Currently
134 // the majority of warnings in headers are false positives. These
135 // are largely caused by configuration state, e.g. preprocessor
136 // defined code, etc.
137 //
138 // Note that this is also a performance optimization. Analyzing
139 // headers many times can be expensive.
140 if (!S.getSourceManager().isInMainFile(Loc: AC.getDecl()->getBeginLoc()))
141 return;
142
143 UnreachableCodeHandler UC(S);
144 reachable_code::FindUnreachableCode(AC, PP&: S.getPreprocessor(), CB&: UC);
145}
146
147namespace {
148/// Warn on logical operator errors in CFGBuilder
149class LogicalErrorHandler : public CFGCallback {
150 Sema &S;
151
152public:
153 LogicalErrorHandler(Sema &S) : S(S) {}
154
155 static bool HasMacroID(const Expr *E) {
156 if (E->getExprLoc().isMacroID())
157 return true;
158
159 // Recurse to children.
160 for (const Stmt *SubStmt : E->children())
161 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(Val: SubStmt))
162 if (HasMacroID(E: SubExpr))
163 return true;
164
165 return false;
166 }
167
168 void logicAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
169 if (HasMacroID(E: B))
170 return;
171
172 unsigned DiagID = isAlwaysTrue
173 ? diag::warn_tautological_negation_or_compare
174 : diag::warn_tautological_negation_and_compare;
175 SourceRange DiagRange = B->getSourceRange();
176 S.Diag(Loc: B->getExprLoc(), DiagID) << DiagRange;
177 }
178
179 void compareAlwaysTrue(const BinaryOperator *B,
180 bool isAlwaysTrueOrFalse) override {
181 if (HasMacroID(E: B))
182 return;
183
184 SourceRange DiagRange = B->getSourceRange();
185 S.Diag(Loc: B->getExprLoc(), DiagID: diag::warn_tautological_overlap_comparison)
186 << DiagRange << isAlwaysTrueOrFalse;
187 }
188
189 void compareBitwiseEquality(const BinaryOperator *B,
190 bool isAlwaysTrue) override {
191 if (HasMacroID(E: B))
192 return;
193
194 SourceRange DiagRange = B->getSourceRange();
195 S.Diag(Loc: B->getExprLoc(), DiagID: diag::warn_comparison_bitwise_always)
196 << DiagRange << isAlwaysTrue;
197 }
198
199 void compareBitwiseOr(const BinaryOperator *B) override {
200 if (HasMacroID(E: B))
201 return;
202
203 SourceRange DiagRange = B->getSourceRange();
204 S.Diag(Loc: B->getExprLoc(), DiagID: diag::warn_comparison_bitwise_or) << DiagRange;
205 }
206
207 static bool hasActiveDiagnostics(DiagnosticsEngine &Diags,
208 SourceLocation Loc) {
209 return !Diags.isIgnored(DiagID: diag::warn_tautological_overlap_comparison, Loc) ||
210 !Diags.isIgnored(DiagID: diag::warn_comparison_bitwise_or, Loc) ||
211 !Diags.isIgnored(DiagID: diag::warn_tautological_negation_and_compare, Loc);
212 }
213};
214} // anonymous namespace
215
216//===----------------------------------------------------------------------===//
217// Check for infinite self-recursion in functions
218//===----------------------------------------------------------------------===//
219
220// Returns true if the function is called anywhere within the CFGBlock.
221// For member functions, the additional condition of being call from the
222// this pointer is required.
223static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
224 // Process all the Stmt's in this block to find any calls to FD.
225 for (const auto &B : Block) {
226 if (B.getKind() != CFGElement::Statement)
227 continue;
228
229 const CallExpr *CE = dyn_cast<CallExpr>(Val: B.getAs<CFGStmt>()->getStmt());
230 if (!CE || !CE->getCalleeDecl() ||
231 CE->getCalleeDecl()->getCanonicalDecl() != FD)
232 continue;
233
234 // Skip function calls which are qualified with a templated class.
235 if (const DeclRefExpr *DRE =
236 dyn_cast<DeclRefExpr>(Val: CE->getCallee()->IgnoreParenImpCasts()))
237 if (NestedNameSpecifier NNS = DRE->getQualifier();
238 NNS.getKind() == NestedNameSpecifier::Kind::Type)
239 if (isa_and_nonnull<TemplateSpecializationType>(Val: NNS.getAsType()))
240 continue;
241
242 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(Val: CE);
243 if (!MCE || isa<CXXThisExpr>(Val: MCE->getImplicitObjectArgument()) ||
244 !MCE->getMethodDecl()->isVirtual())
245 return true;
246 }
247 return false;
248}
249
250// Returns true if every path from the entry block passes through a call to FD.
251static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
252 llvm::SmallPtrSet<CFGBlock *, 16> Visited;
253 llvm::SmallVector<CFGBlock *, 16> WorkList;
254 // Keep track of whether we found at least one recursive path.
255 bool foundRecursion = false;
256
257 const unsigned ExitID = cfg->getExit().getBlockID();
258
259 // Seed the work list with the entry block.
260 WorkList.push_back(Elt: &cfg->getEntry());
261
262 while (!WorkList.empty()) {
263 CFGBlock *Block = WorkList.pop_back_val();
264
265 for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
266 if (CFGBlock *SuccBlock = *I) {
267 if (!Visited.insert(Ptr: SuccBlock).second)
268 continue;
269
270 // Found a path to the exit node without a recursive call.
271 if (ExitID == SuccBlock->getBlockID())
272 return false;
273
274 // If the successor block contains a recursive call, end analysis there.
275 if (hasRecursiveCallInPath(FD, Block&: *SuccBlock)) {
276 foundRecursion = true;
277 continue;
278 }
279
280 WorkList.push_back(Elt: SuccBlock);
281 }
282 }
283 }
284 return foundRecursion;
285}
286
287static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
288 const Stmt *Body, AnalysisDeclContext &AC) {
289 FD = FD->getCanonicalDecl();
290
291 // Only run on non-templated functions and non-templated members of
292 // templated classes.
293 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
294 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
295 return;
296
297 CFG *cfg = AC.getCFG();
298 if (!cfg) return;
299
300 // If the exit block is unreachable, skip processing the function.
301 if (cfg->getExit().pred_empty())
302 return;
303
304 // Emit diagnostic if a recursive function call is detected for all paths.
305 if (checkForRecursiveFunctionCall(FD, cfg))
306 S.Diag(Loc: Body->getBeginLoc(), DiagID: diag::warn_infinite_recursive_function);
307}
308
309//===----------------------------------------------------------------------===//
310// Check for throw in a non-throwing function.
311//===----------------------------------------------------------------------===//
312
313/// Determine whether an exception thrown by E, unwinding from ThrowBlock,
314/// can reach ExitBlock.
315static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
316 CFG *Body) {
317 SmallVector<CFGBlock *, 16> Stack;
318 llvm::BitVector Queued(Body->getNumBlockIDs());
319
320 Stack.push_back(Elt: &ThrowBlock);
321 Queued[ThrowBlock.getBlockID()] = true;
322
323 while (!Stack.empty()) {
324 CFGBlock &UnwindBlock = *Stack.pop_back_val();
325
326 for (auto &Succ : UnwindBlock.succs()) {
327 if (!Succ.isReachable() || Queued[Succ->getBlockID()])
328 continue;
329
330 if (Succ->getBlockID() == Body->getExit().getBlockID())
331 return true;
332
333 if (auto *Catch =
334 dyn_cast_or_null<CXXCatchStmt>(Val: Succ->getLabel())) {
335 QualType Caught = Catch->getCaughtType();
336 if (Caught.isNull() || // catch (...) catches everything
337 !E->getSubExpr() || // throw; is considered cuaght by any handler
338 S.handlerCanCatch(HandlerType: Caught, ExceptionType: E->getSubExpr()->getType()))
339 // Exception doesn't escape via this path.
340 break;
341 } else {
342 Stack.push_back(Elt: Succ);
343 Queued[Succ->getBlockID()] = true;
344 }
345 }
346 }
347
348 return false;
349}
350
351static void visitReachableThrows(
352 CFG *BodyCFG,
353 llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
354 llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
355 clang::reachable_code::ScanReachableFromBlock(Start: &BodyCFG->getEntry(), Reachable);
356 for (CFGBlock *B : *BodyCFG) {
357 if (!Reachable[B->getBlockID()])
358 continue;
359 for (CFGElement &E : *B) {
360 std::optional<CFGStmt> S = E.getAs<CFGStmt>();
361 if (!S)
362 continue;
363 if (auto *Throw = dyn_cast<CXXThrowExpr>(Val: S->getStmt()))
364 Visit(Throw, *B);
365 }
366 }
367}
368
369static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
370 const FunctionDecl *FD) {
371 if (!S.getSourceManager().isInSystemHeader(Loc: OpLoc) &&
372 FD->getTypeSourceInfo()) {
373 S.Diag(Loc: OpLoc, DiagID: diag::warn_throw_in_noexcept_func) << FD;
374 if (S.getLangOpts().CPlusPlus11 &&
375 (isa<CXXDestructorDecl>(Val: FD) ||
376 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
377 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
378 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
379 getAs<FunctionProtoType>())
380 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_throw_in_dtor)
381 << !isa<CXXDestructorDecl>(Val: FD) << !Ty->hasExceptionSpec()
382 << FD->getExceptionSpecSourceRange();
383 } else
384 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_throw_in_function)
385 << FD->getExceptionSpecSourceRange();
386 }
387}
388
389static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
390 AnalysisDeclContext &AC) {
391 CFG *BodyCFG = AC.getCFG();
392 if (!BodyCFG)
393 return;
394 if (BodyCFG->getExit().pred_empty())
395 return;
396 visitReachableThrows(BodyCFG, Visit: [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
397 if (throwEscapes(S, E: Throw, ThrowBlock&: Block, Body: BodyCFG))
398 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc: Throw->getThrowLoc(), FD);
399 });
400}
401
402static bool isNoexcept(const FunctionDecl *FD) {
403 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
404 if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
405 return true;
406 return false;
407}
408
409/// Checks if the given expression is a reference to a function with
410/// 'noreturn' attribute.
411static bool isReferenceToNoReturn(const Expr *E) {
412 if (auto *DRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenCasts()))
413 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRef->getDecl()))
414 return FD->isNoReturn();
415 return false;
416}
417
418/// Checks if the given variable, which is assumed to be a function pointer, is
419/// initialized with a function having 'noreturn' attribute.
420static bool isInitializedWithNoReturn(const VarDecl *VD) {
421 if (const Expr *Init = VD->getInit()) {
422 if (auto *ListInit = dyn_cast<InitListExpr>(Val: Init);
423 ListInit && ListInit->getNumInits() > 0)
424 Init = ListInit->getInit(Init: 0);
425 return isReferenceToNoReturn(E: Init);
426 }
427 return false;
428}
429
430namespace {
431
432/// Looks for statements, that can define value of the given variable.
433struct TransferFunctions : public StmtVisitor<TransferFunctions> {
434 const VarDecl *Var;
435 std::optional<bool> AllValuesAreNoReturn;
436
437 TransferFunctions(const VarDecl *VD) : Var(VD) {}
438
439 void reset() { AllValuesAreNoReturn = std::nullopt; }
440
441 void VisitDeclStmt(DeclStmt *DS) {
442 for (auto *DI : DS->decls())
443 if (auto *VD = dyn_cast<VarDecl>(Val: DI))
444 if (VarDecl *Def = VD->getDefinition())
445 if (Def == Var)
446 AllValuesAreNoReturn = isInitializedWithNoReturn(VD: Def);
447 }
448
449 void VisitUnaryOperator(UnaryOperator *UO) {
450 if (UO->getOpcode() == UO_AddrOf) {
451 if (auto *DRef =
452 dyn_cast<DeclRefExpr>(Val: UO->getSubExpr()->IgnoreParenCasts()))
453 if (DRef->getDecl() == Var)
454 AllValuesAreNoReturn = false;
455 }
456 }
457
458 void VisitBinaryOperator(BinaryOperator *BO) {
459 if (BO->getOpcode() == BO_Assign)
460 if (auto *DRef = dyn_cast<DeclRefExpr>(Val: BO->getLHS()->IgnoreParenCasts()))
461 if (DRef->getDecl() == Var)
462 AllValuesAreNoReturn = isReferenceToNoReturn(E: BO->getRHS());
463 }
464
465 void VisitCallExpr(CallExpr *CE) {
466 for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E;
467 ++I) {
468 const Expr *Arg = *I;
469 if (Arg->isGLValue() && !Arg->getType().isConstQualified())
470 if (auto *DRef = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenCasts()))
471 if (auto VD = dyn_cast<VarDecl>(Val: DRef->getDecl()))
472 if (VD->getDefinition() == Var)
473 AllValuesAreNoReturn = false;
474 }
475 }
476};
477} // namespace
478
479// Checks if all possible values of the given variable are functions with
480// 'noreturn' attribute.
481static bool areAllValuesNoReturn(const VarDecl *VD, const CFGBlock &VarBlk,
482 AnalysisDeclContext &AC) {
483 // The set of possible values of a constant variable is determined by
484 // its initializer, unless it is a function parameter.
485 if (!isa<ParmVarDecl>(Val: VD) && VD->getType().isConstant(Ctx: AC.getASTContext())) {
486 if (const VarDecl *Def = VD->getDefinition())
487 return isInitializedWithNoReturn(VD: Def);
488 return false;
489 }
490
491 // In multithreaded environment the value of a global variable may be changed
492 // asynchronously.
493 if (!VD->getDeclContext()->isFunctionOrMethod())
494 return false;
495
496 // Check the condition "all values are noreturn". It is satisfied if the
497 // variable is set to "noreturn" value in the current block or all its
498 // predecessors satisfies the condition.
499 using MapTy = llvm::DenseMap<const CFGBlock *, std::optional<bool>>;
500 using ValueTy = MapTy::value_type;
501 MapTy BlocksToCheck;
502 BlocksToCheck[&VarBlk] = std::nullopt;
503 const auto BlockSatisfiesCondition = [](ValueTy Item) {
504 return Item.getSecond().value_or(u: false);
505 };
506
507 TransferFunctions TF(VD);
508 BackwardDataflowWorklist Worklist(*AC.getCFG(), AC);
509 llvm::DenseSet<const CFGBlock *> Visited;
510 Worklist.enqueueBlock(Block: &VarBlk);
511 while (const CFGBlock *B = Worklist.dequeue()) {
512 if (Visited.contains(V: B))
513 continue;
514 Visited.insert(V: B);
515 // First check the current block.
516 for (CFGBlock::const_reverse_iterator ri = B->rbegin(), re = B->rend();
517 ri != re; ++ri) {
518 if (std::optional<CFGStmt> cs = ri->getAs<CFGStmt>()) {
519 const Stmt *S = cs->getStmt();
520 TF.reset();
521 TF.Visit(S: const_cast<Stmt *>(S));
522 if (TF.AllValuesAreNoReturn) {
523 if (!TF.AllValuesAreNoReturn.value())
524 return false;
525 BlocksToCheck[B] = true;
526 break;
527 }
528 }
529 }
530
531 // If all checked blocks satisfy the condition, the check is finished.
532 if (llvm::all_of(Range&: BlocksToCheck, P: BlockSatisfiesCondition))
533 return true;
534
535 // If this block does not contain the variable definition, check
536 // its predecessors.
537 if (!BlocksToCheck[B]) {
538 Worklist.enqueuePredecessors(Block: B);
539 BlocksToCheck.erase(Val: B);
540 for (const auto &PredBlk : B->preds())
541 if (!BlocksToCheck.contains(Val: PredBlk))
542 BlocksToCheck[PredBlk] = std::nullopt;
543 }
544 }
545
546 return false;
547}
548
549//===----------------------------------------------------------------------===//
550// Check for missing return value.
551//===----------------------------------------------------------------------===//
552
553enum ControlFlowKind {
554 UnknownFallThrough,
555 NeverFallThrough,
556 MaybeFallThrough,
557 AlwaysFallThrough,
558 NeverFallThroughOrReturn
559};
560
561/// CheckFallThrough - Check that we don't fall off the end of a
562/// Statement that should return a value.
563///
564/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
565/// MaybeFallThrough iff we might or might not fall off the end,
566/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
567/// return. We assume NeverFallThrough iff we never fall off the end of the
568/// statement but we may return. We assume that functions not marked noreturn
569/// will return.
570static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
571 CFG *cfg = AC.getCFG();
572 if (!cfg) return UnknownFallThrough;
573
574 // The CFG leaves in dead things, and we don't want the dead code paths to
575 // confuse us, so we mark all live things first.
576 llvm::BitVector live(cfg->getNumBlockIDs());
577 unsigned count =
578 reachable_code::ScanReachableFromBlock(Start: &cfg->getEntry(), Reachable&: live);
579
580 bool AddEHEdges = AC.getAddEHEdges();
581 if (!AddEHEdges && count != cfg->getNumBlockIDs())
582 // When there are things remaining dead, and we didn't add EH edges
583 // from CallExprs to the catch clauses, we have to go back and
584 // mark them as live.
585 for (const auto *B : *cfg) {
586 if (!live[B->getBlockID()]) {
587 if (B->preds().empty()) {
588 const Stmt *Term = B->getTerminatorStmt();
589 if (isa_and_nonnull<CXXTryStmt>(Val: Term))
590 // When not adding EH edges from calls, catch clauses
591 // can otherwise seem dead. Avoid noting them as dead.
592 count += reachable_code::ScanReachableFromBlock(Start: B, Reachable&: live);
593 continue;
594 }
595 }
596 }
597
598 // Now we know what is live, we check the live precessors of the exit block
599 // and look for fall through paths, being careful to ignore normal returns,
600 // and exceptional paths.
601 bool HasLiveReturn = false;
602 bool HasFakeEdge = false;
603 bool HasPlainEdge = false;
604 bool HasAbnormalEdge = false;
605
606 // Ignore default cases that aren't likely to be reachable because all
607 // enums in a switch(X) have explicit case statements.
608 CFGBlock::FilterOptions FO;
609 FO.IgnoreDefaultsWithCoveredEnums = 1;
610
611 for (CFGBlock::filtered_pred_iterator I =
612 cfg->getExit().filtered_pred_start_end(f: FO);
613 I.hasMore(); ++I) {
614 const CFGBlock &B = **I;
615 if (!live[B.getBlockID()])
616 continue;
617
618 // Skip blocks which contain an element marked as no-return. They don't
619 // represent actually viable edges into the exit block, so mark them as
620 // abnormal.
621 if (B.hasNoReturnElement()) {
622 HasAbnormalEdge = true;
623 continue;
624 }
625
626 // Destructors can appear after the 'return' in the CFG. This is
627 // normal. We need to look pass the destructors for the return
628 // statement (if it exists).
629 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
630
631 for ( ; ri != re ; ++ri)
632 if (ri->getAs<CFGStmt>())
633 break;
634
635 // No more CFGElements in the block?
636 if (ri == re) {
637 const Stmt *Term = B.getTerminatorStmt();
638 if (Term && (isa<CXXTryStmt>(Val: Term) || isa<ObjCAtTryStmt>(Val: Term))) {
639 HasAbnormalEdge = true;
640 continue;
641 }
642 // A labeled empty statement, or the entry block...
643 HasPlainEdge = true;
644 continue;
645 }
646
647 CFGStmt CS = ri->castAs<CFGStmt>();
648 const Stmt *S = CS.getStmt();
649 if (isa<ReturnStmt>(Val: S) || isa<CoreturnStmt>(Val: S)) {
650 HasLiveReturn = true;
651 continue;
652 }
653 if (isa<ObjCAtThrowStmt>(Val: S)) {
654 HasFakeEdge = true;
655 continue;
656 }
657 if (isa<CXXThrowExpr>(Val: S)) {
658 HasFakeEdge = true;
659 continue;
660 }
661 if (isa<MSAsmStmt>(Val: S)) {
662 // TODO: Verify this is correct.
663 HasFakeEdge = true;
664 HasLiveReturn = true;
665 continue;
666 }
667 if (isa<CXXTryStmt>(Val: S)) {
668 HasAbnormalEdge = true;
669 continue;
670 }
671 if (!llvm::is_contained(Range: B.succs(), Element: &cfg->getExit())) {
672 HasAbnormalEdge = true;
673 continue;
674 }
675 if (auto *Call = dyn_cast<CallExpr>(Val: S)) {
676 const Expr *Callee = Call->getCallee();
677 if (Callee->getType()->isPointerType())
678 if (auto *DeclRef =
679 dyn_cast<DeclRefExpr>(Val: Callee->IgnoreParenImpCasts()))
680 if (auto *VD = dyn_cast<VarDecl>(Val: DeclRef->getDecl()))
681 if (areAllValuesNoReturn(VD, VarBlk: B, AC)) {
682 HasAbnormalEdge = true;
683 continue;
684 }
685 }
686
687 HasPlainEdge = true;
688 }
689 if (!HasPlainEdge) {
690 if (HasLiveReturn)
691 return NeverFallThrough;
692 return NeverFallThroughOrReturn;
693 }
694 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
695 return MaybeFallThrough;
696 // This says AlwaysFallThrough for calls to functions that are not marked
697 // noreturn, that don't return. If people would like this warning to be more
698 // accurate, such functions should be marked as noreturn.
699 return AlwaysFallThrough;
700}
701
702namespace {
703
704struct CheckFallThroughDiagnostics {
705 unsigned diag_FallThrough_HasNoReturn = 0;
706 unsigned diag_FallThrough_ReturnsNonVoid = 0;
707 unsigned diag_NeverFallThroughOrReturn = 0;
708 unsigned FunKind; // TODO: use diag::FalloffFunctionKind
709 SourceLocation FuncLoc;
710
711 static CheckFallThroughDiagnostics MakeForFunction(Sema &S,
712 const Decl *Func) {
713 CheckFallThroughDiagnostics D;
714 D.FuncLoc = Func->getLocation();
715 D.diag_FallThrough_HasNoReturn = diag::warn_noreturn_has_return_expr;
716 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
717
718 // Don't suggest that virtual functions be marked "noreturn", since they
719 // might be overridden by non-noreturn functions.
720 bool isVirtualMethod = false;
721 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Func))
722 isVirtualMethod = Method->isVirtual();
723
724 // Don't suggest that template instantiations be marked "noreturn"
725 bool isTemplateInstantiation = false;
726 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Func)) {
727 isTemplateInstantiation = Function->isTemplateInstantiation();
728 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C99 &&
729 Function->isMain()) {
730 D.diag_FallThrough_ReturnsNonVoid = diag::ext_main_no_return;
731 }
732 }
733
734 if (!isVirtualMethod && !isTemplateInstantiation)
735 D.diag_NeverFallThroughOrReturn = diag::warn_suggest_noreturn_function;
736
737 D.FunKind = diag::FalloffFunctionKind::Function;
738 return D;
739 }
740
741 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
742 CheckFallThroughDiagnostics D;
743 D.FuncLoc = Func->getLocation();
744 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
745 D.FunKind = diag::FalloffFunctionKind::Coroutine;
746 return D;
747 }
748
749 static CheckFallThroughDiagnostics MakeForBlock() {
750 CheckFallThroughDiagnostics D;
751 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr;
752 D.diag_FallThrough_ReturnsNonVoid = diag::err_falloff_nonvoid;
753 D.FunKind = diag::FalloffFunctionKind::Block;
754 return D;
755 }
756
757 static CheckFallThroughDiagnostics MakeForLambda() {
758 CheckFallThroughDiagnostics D;
759 D.diag_FallThrough_HasNoReturn = diag::err_noreturn_has_return_expr;
760 D.diag_FallThrough_ReturnsNonVoid = diag::warn_falloff_nonvoid;
761 D.FunKind = diag::FalloffFunctionKind::Lambda;
762 return D;
763 }
764
765 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
766 bool HasNoReturn) const {
767 if (FunKind == diag::FalloffFunctionKind::Function) {
768 return (ReturnsVoid ||
769 D.isIgnored(DiagID: diag::warn_falloff_nonvoid, Loc: FuncLoc)) &&
770 (!HasNoReturn ||
771 D.isIgnored(DiagID: diag::warn_noreturn_has_return_expr, Loc: FuncLoc)) &&
772 (!ReturnsVoid ||
773 D.isIgnored(DiagID: diag::warn_suggest_noreturn_block, Loc: FuncLoc));
774 }
775 if (FunKind == diag::FalloffFunctionKind::Coroutine) {
776 return (ReturnsVoid ||
777 D.isIgnored(DiagID: diag::warn_falloff_nonvoid, Loc: FuncLoc)) &&
778 (!HasNoReturn);
779 }
780 // For blocks / lambdas.
781 return ReturnsVoid && !HasNoReturn;
782 }
783};
784
785} // anonymous namespace
786
787/// CheckFallThroughForBody - Check that we don't fall off the end of a
788/// function that should return a value. Check that we don't fall off the end
789/// of a noreturn function. We assume that functions and blocks not marked
790/// noreturn will return.
791static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
792 QualType BlockType,
793 const CheckFallThroughDiagnostics &CD,
794 AnalysisDeclContext &AC) {
795
796 bool ReturnsVoid = false;
797 bool HasNoReturn = false;
798
799 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
800 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Val: Body))
801 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
802 else
803 ReturnsVoid = FD->getReturnType()->isVoidType();
804 HasNoReturn = FD->isNoReturn() || FD->hasAttr<InferredNoReturnAttr>();
805 }
806 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
807 ReturnsVoid = MD->getReturnType()->isVoidType();
808 HasNoReturn = MD->hasAttr<NoReturnAttr>();
809 }
810 else if (isa<BlockDecl>(Val: D)) {
811 if (const FunctionType *FT =
812 BlockType->getPointeeType()->getAs<FunctionType>()) {
813 if (FT->getReturnType()->isVoidType())
814 ReturnsVoid = true;
815 if (FT->getNoReturnAttr())
816 HasNoReturn = true;
817 }
818 }
819
820 DiagnosticsEngine &Diags = S.getDiagnostics();
821
822 // Short circuit for compilation speed.
823 if (CD.checkDiagnostics(D&: Diags, ReturnsVoid, HasNoReturn))
824 return;
825 SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
826
827 // cpu_dispatch functions permit empty function bodies for ICC compatibility.
828 if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
829 return;
830
831 // Either in a function body compound statement, or a function-try-block.
832 switch (int FallThroughType = CheckFallThrough(AC)) {
833 case UnknownFallThrough:
834 break;
835
836 case MaybeFallThrough:
837 case AlwaysFallThrough:
838 if (HasNoReturn) {
839 if (CD.diag_FallThrough_HasNoReturn)
840 S.Diag(Loc: RBrace, DiagID: CD.diag_FallThrough_HasNoReturn) << CD.FunKind;
841 } else if (!ReturnsVoid && CD.diag_FallThrough_ReturnsNonVoid) {
842 // If the final statement is a call to an always-throwing function,
843 // don't warn about the fall-through.
844 if (D->getAsFunction()) {
845 if (const auto *CS = dyn_cast<CompoundStmt>(Val: Body);
846 CS && !CS->body_empty()) {
847 const Stmt *LastStmt = CS->body_back();
848 // Unwrap ExprWithCleanups if necessary.
849 if (const auto *EWC = dyn_cast<ExprWithCleanups>(Val: LastStmt)) {
850 LastStmt = EWC->getSubExpr();
851 }
852 if (const auto *CE = dyn_cast<CallExpr>(Val: LastStmt)) {
853 if (const FunctionDecl *Callee = CE->getDirectCallee();
854 Callee && Callee->hasAttr<InferredNoReturnAttr>()) {
855 return; // Don't warn about fall-through.
856 }
857 }
858 // Direct throw.
859 if (isa<CXXThrowExpr>(Val: LastStmt)) {
860 return; // Don't warn about fall-through.
861 }
862 }
863 }
864 bool NotInAllControlPaths = FallThroughType == MaybeFallThrough;
865 S.Diag(Loc: RBrace, DiagID: CD.diag_FallThrough_ReturnsNonVoid)
866 << CD.FunKind << NotInAllControlPaths;
867 }
868 break;
869 case NeverFallThroughOrReturn:
870 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
872 S.Diag(Loc: LBrace, DiagID: CD.diag_NeverFallThroughOrReturn) << 0 << FD;
873 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
874 S.Diag(Loc: LBrace, DiagID: CD.diag_NeverFallThroughOrReturn) << 1 << MD;
875 } else {
876 S.Diag(Loc: LBrace, DiagID: CD.diag_NeverFallThroughOrReturn);
877 }
878 }
879 break;
880 case NeverFallThrough:
881 break;
882 }
883}
884
885//===----------------------------------------------------------------------===//
886// -Wuninitialized
887//===----------------------------------------------------------------------===//
888
889namespace {
890/// ContainsReference - A visitor class to search for references to
891/// a particular declaration (the needle) within any evaluated component of an
892/// expression (recursively).
893class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
894 bool FoundReference;
895 const DeclRefExpr *Needle;
896
897public:
898 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
899
900 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
901 : Inherited(Context), FoundReference(false), Needle(Needle) {}
902
903 void VisitExpr(const Expr *E) {
904 // Stop evaluating if we already have a reference.
905 if (FoundReference)
906 return;
907
908 Inherited::VisitExpr(S: E);
909 }
910
911 void VisitDeclRefExpr(const DeclRefExpr *E) {
912 if (E == Needle)
913 FoundReference = true;
914 else
915 Inherited::VisitDeclRefExpr(E);
916 }
917
918 bool doesContainReference() const { return FoundReference; }
919};
920} // anonymous namespace
921
922static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
923 QualType VariableTy = VD->getType().getCanonicalType();
924 if (VariableTy->isBlockPointerType() &&
925 !VD->hasAttr<BlocksAttr>()) {
926 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_block_var_fixit_add_initialization)
927 << VD->getDeclName()
928 << FixItHint::CreateInsertion(InsertionLoc: VD->getLocation(), Code: "__block ");
929 return true;
930 }
931
932 // Don't issue a fixit if there is already an initializer.
933 if (VD->getInit())
934 return false;
935
936 // Don't suggest a fixit inside macros.
937 if (VD->getEndLoc().isMacroID())
938 return false;
939
940 SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc());
941
942 // Suggest possible initialization (if any).
943 std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc);
944 if (Init.empty())
945 return false;
946
947 S.Diag(Loc, DiagID: diag::note_var_fixit_add_initialization) << VD->getDeclName()
948 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: Init);
949 return true;
950}
951
952/// Create a fixit to remove an if-like statement, on the assumption that its
953/// condition is CondVal.
954static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
955 const Stmt *Else, bool CondVal,
956 FixItHint &Fixit1, FixItHint &Fixit2) {
957 if (CondVal) {
958 // If condition is always true, remove all but the 'then'.
959 Fixit1 = FixItHint::CreateRemoval(
960 RemoveRange: CharSourceRange::getCharRange(B: If->getBeginLoc(), E: Then->getBeginLoc()));
961 if (Else) {
962 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Loc: Then->getEndLoc());
963 Fixit2 =
964 FixItHint::CreateRemoval(RemoveRange: SourceRange(ElseKwLoc, Else->getEndLoc()));
965 }
966 } else {
967 // If condition is always false, remove all but the 'else'.
968 if (Else)
969 Fixit1 = FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
970 B: If->getBeginLoc(), E: Else->getBeginLoc()));
971 else
972 Fixit1 = FixItHint::CreateRemoval(RemoveRange: If->getSourceRange());
973 }
974}
975
976/// DiagUninitUse -- Helper function to produce a diagnostic for an
977/// uninitialized use of a variable.
978static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
979 bool IsCapturedByBlock) {
980 bool Diagnosed = false;
981
982 switch (Use.getKind()) {
983 case UninitUse::Always:
984 S.Diag(Loc: Use.getUser()->getBeginLoc(), DiagID: diag::warn_uninit_var)
985 << VD->getDeclName() << IsCapturedByBlock
986 << Use.getUser()->getSourceRange();
987 return;
988
989 case UninitUse::AfterDecl:
990 case UninitUse::AfterCall:
991 S.Diag(Loc: VD->getLocation(), DiagID: diag::warn_sometimes_uninit_var)
992 << VD->getDeclName() << IsCapturedByBlock
993 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
994 << VD->getLexicalDeclContext() << VD->getSourceRange();
995 S.Diag(Loc: Use.getUser()->getBeginLoc(), DiagID: diag::note_uninit_var_use)
996 << IsCapturedByBlock << Use.getUser()->getSourceRange();
997 return;
998
999 case UninitUse::Maybe:
1000 case UninitUse::Sometimes:
1001 // Carry on to report sometimes-uninitialized branches, if possible,
1002 // or a 'may be used uninitialized' diagnostic otherwise.
1003 break;
1004 }
1005
1006 // Diagnose each branch which leads to a sometimes-uninitialized use.
1007 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
1008 I != E; ++I) {
1009 assert(Use.getKind() == UninitUse::Sometimes);
1010
1011 const Expr *User = Use.getUser();
1012 const Stmt *Term = I->Terminator;
1013
1014 // Information used when building the diagnostic.
1015 unsigned DiagKind;
1016 StringRef Str;
1017 SourceRange Range;
1018
1019 // FixIts to suppress the diagnostic by removing the dead condition.
1020 // For all binary terminators, branch 0 is taken if the condition is true,
1021 // and branch 1 is taken if the condition is false.
1022 int RemoveDiagKind = -1;
1023 const char *FixitStr =
1024 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
1025 : (I->Output ? "1" : "0");
1026 FixItHint Fixit1, Fixit2;
1027
1028 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
1029 default:
1030 // Don't know how to report this. Just fall back to 'may be used
1031 // uninitialized'. FIXME: Can this happen?
1032 continue;
1033
1034 // "condition is true / condition is false".
1035 case Stmt::IfStmtClass: {
1036 const IfStmt *IS = cast<IfStmt>(Val: Term);
1037 DiagKind = 0;
1038 Str = "if";
1039 Range = IS->getCond()->getSourceRange();
1040 RemoveDiagKind = 0;
1041 CreateIfFixit(S, If: IS, Then: IS->getThen(), Else: IS->getElse(),
1042 CondVal: I->Output, Fixit1, Fixit2);
1043 break;
1044 }
1045 case Stmt::ConditionalOperatorClass: {
1046 const ConditionalOperator *CO = cast<ConditionalOperator>(Val: Term);
1047 DiagKind = 0;
1048 Str = "?:";
1049 Range = CO->getCond()->getSourceRange();
1050 RemoveDiagKind = 0;
1051 CreateIfFixit(S, If: CO, Then: CO->getTrueExpr(), Else: CO->getFalseExpr(),
1052 CondVal: I->Output, Fixit1, Fixit2);
1053 break;
1054 }
1055 case Stmt::BinaryOperatorClass: {
1056 const BinaryOperator *BO = cast<BinaryOperator>(Val: Term);
1057 if (!BO->isLogicalOp())
1058 continue;
1059 DiagKind = 0;
1060 Str = BO->getOpcodeStr();
1061 Range = BO->getLHS()->getSourceRange();
1062 RemoveDiagKind = 0;
1063 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
1064 (BO->getOpcode() == BO_LOr && !I->Output))
1065 // true && y -> y, false || y -> y.
1066 Fixit1 = FixItHint::CreateRemoval(
1067 RemoveRange: SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
1068 else
1069 // false && y -> false, true || y -> true.
1070 Fixit1 = FixItHint::CreateReplacement(RemoveRange: BO->getSourceRange(), Code: FixitStr);
1071 break;
1072 }
1073
1074 // "loop is entered / loop is exited".
1075 case Stmt::WhileStmtClass:
1076 DiagKind = 1;
1077 Str = "while";
1078 Range = cast<WhileStmt>(Val: Term)->getCond()->getSourceRange();
1079 RemoveDiagKind = 1;
1080 Fixit1 = FixItHint::CreateReplacement(RemoveRange: Range, Code: FixitStr);
1081 break;
1082 case Stmt::ForStmtClass:
1083 DiagKind = 1;
1084 Str = "for";
1085 Range = cast<ForStmt>(Val: Term)->getCond()->getSourceRange();
1086 RemoveDiagKind = 1;
1087 if (I->Output)
1088 Fixit1 = FixItHint::CreateRemoval(RemoveRange: Range);
1089 else
1090 Fixit1 = FixItHint::CreateReplacement(RemoveRange: Range, Code: FixitStr);
1091 break;
1092 case Stmt::CXXForRangeStmtClass:
1093 if (I->Output == 1) {
1094 // The use occurs if a range-based for loop's body never executes.
1095 // That may be impossible, and there's no syntactic fix for this,
1096 // so treat it as a 'may be uninitialized' case.
1097 continue;
1098 }
1099 DiagKind = 1;
1100 Str = "for";
1101 Range = cast<CXXForRangeStmt>(Val: Term)->getRangeInit()->getSourceRange();
1102 break;
1103
1104 // "condition is true / loop is exited".
1105 case Stmt::DoStmtClass:
1106 DiagKind = 2;
1107 Str = "do";
1108 Range = cast<DoStmt>(Val: Term)->getCond()->getSourceRange();
1109 RemoveDiagKind = 1;
1110 Fixit1 = FixItHint::CreateReplacement(RemoveRange: Range, Code: FixitStr);
1111 break;
1112
1113 // "switch case is taken".
1114 case Stmt::CaseStmtClass:
1115 DiagKind = 3;
1116 Str = "case";
1117 Range = cast<CaseStmt>(Val: Term)->getLHS()->getSourceRange();
1118 break;
1119 case Stmt::DefaultStmtClass:
1120 DiagKind = 3;
1121 Str = "default";
1122 Range = cast<DefaultStmt>(Val: Term)->getDefaultLoc();
1123 break;
1124 }
1125
1126 S.Diag(Loc: Range.getBegin(), DiagID: diag::warn_sometimes_uninit_var)
1127 << VD->getDeclName() << IsCapturedByBlock << DiagKind
1128 << Str << I->Output << Range;
1129 S.Diag(Loc: User->getBeginLoc(), DiagID: diag::note_uninit_var_use)
1130 << IsCapturedByBlock << User->getSourceRange();
1131 if (RemoveDiagKind != -1)
1132 S.Diag(Loc: Fixit1.RemoveRange.getBegin(), DiagID: diag::note_uninit_fixit_remove_cond)
1133 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1134
1135 Diagnosed = true;
1136 }
1137
1138 if (!Diagnosed)
1139 S.Diag(Loc: Use.getUser()->getBeginLoc(), DiagID: diag::warn_maybe_uninit_var)
1140 << VD->getDeclName() << IsCapturedByBlock
1141 << Use.getUser()->getSourceRange();
1142}
1143
1144/// Diagnose uninitialized const reference usages.
1145static bool DiagnoseUninitializedConstRefUse(Sema &S, const VarDecl *VD,
1146 const UninitUse &Use) {
1147 S.Diag(Loc: Use.getUser()->getBeginLoc(), DiagID: diag::warn_uninit_const_reference)
1148 << VD->getDeclName() << Use.getUser()->getSourceRange();
1149 return !S.getDiagnostics().isLastDiagnosticIgnored();
1150}
1151
1152/// Diagnose uninitialized const pointer usages.
1153static bool DiagnoseUninitializedConstPtrUse(Sema &S, const VarDecl *VD,
1154 const UninitUse &Use) {
1155 S.Diag(Loc: Use.getUser()->getBeginLoc(), DiagID: diag::warn_uninit_const_pointer)
1156 << VD->getDeclName() << Use.getUser()->getSourceRange();
1157 return !S.getDiagnostics().isLastDiagnosticIgnored();
1158}
1159
1160/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1161/// uninitialized variable. This manages the different forms of diagnostic
1162/// emitted for particular types of uses. Returns true if the use was diagnosed
1163/// as a warning. If a particular use is one we omit warnings for, returns
1164/// false.
1165static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
1166 const UninitUse &Use,
1167 bool alwaysReportSelfInit = false) {
1168 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Use.getUser())) {
1169 // Inspect the initializer of the variable declaration which is
1170 // being referenced prior to its initialization. We emit
1171 // specialized diagnostics for self-initialization, and we
1172 // specifically avoid warning about self references which take the
1173 // form of:
1174 //
1175 // int x = x;
1176 //
1177 // This is used to indicate to GCC that 'x' is intentionally left
1178 // uninitialized. Proven code paths which access 'x' in
1179 // an uninitialized state after this will still warn.
1180 if (const Expr *Initializer = VD->getInit()) {
1181 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1182 return false;
1183
1184 ContainsReference CR(S.Context, DRE);
1185 CR.Visit(S: Initializer);
1186 if (CR.doesContainReference()) {
1187 S.Diag(Loc: DRE->getBeginLoc(), DiagID: diag::warn_uninit_self_reference_in_init)
1188 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1189 return !S.getDiagnostics().isLastDiagnosticIgnored();
1190 }
1191 }
1192
1193 DiagUninitUse(S, VD, Use, IsCapturedByBlock: false);
1194 } else {
1195 const BlockExpr *BE = cast<BlockExpr>(Val: Use.getUser());
1196 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1197 S.Diag(Loc: BE->getBeginLoc(),
1198 DiagID: diag::warn_uninit_byref_blockvar_captured_by_block)
1199 << VD->getDeclName()
1200 << VD->getType().getQualifiers().hasObjCLifetime();
1201 else
1202 DiagUninitUse(S, VD, Use, IsCapturedByBlock: true);
1203 }
1204
1205 // Report where the variable was declared when the use wasn't within
1206 // the initializer of that declaration & we didn't already suggest
1207 // an initialization fixit.
1208 if (!SuggestInitializationFixit(S, VD))
1209 S.Diag(Loc: VD->getBeginLoc(), DiagID: diag::note_var_declared_here)
1210 << VD->getDeclName();
1211
1212 return !S.getDiagnostics().isLastDiagnosticIgnored();
1213}
1214
1215namespace {
1216class FallthroughMapper : public DynamicRecursiveASTVisitor {
1217public:
1218 FallthroughMapper(Sema &S) : FoundSwitchStatements(false), S(S) {
1219 ShouldWalkTypesOfTypeLocs = false;
1220 }
1221
1222 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1223
1224 void markFallthroughVisited(const AttributedStmt *Stmt) {
1225 bool Found = FallthroughStmts.erase(Ptr: Stmt);
1226 assert(Found);
1227 (void)Found;
1228 }
1229
1230 typedef llvm::SmallPtrSet<const AttributedStmt *, 8> AttrStmts;
1231
1232 const AttrStmts &getFallthroughStmts() const { return FallthroughStmts; }
1233
1234 void fillReachableBlocks(CFG *Cfg) {
1235 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1236 std::deque<const CFGBlock *> BlockQueue;
1237
1238 ReachableBlocks.insert(Ptr: &Cfg->getEntry());
1239 BlockQueue.push_back(x: &Cfg->getEntry());
1240 // Mark all case blocks reachable to avoid problems with switching on
1241 // constants, covered enums, etc.
1242 // These blocks can contain fall-through annotations, and we don't want to
1243 // issue a warn_fallthrough_attr_unreachable for them.
1244 for (const auto *B : *Cfg) {
1245 const Stmt *L = B->getLabel();
1246 if (isa_and_nonnull<SwitchCase>(Val: L) && ReachableBlocks.insert(Ptr: B).second)
1247 BlockQueue.push_back(x: B);
1248 }
1249
1250 while (!BlockQueue.empty()) {
1251 const CFGBlock *P = BlockQueue.front();
1252 BlockQueue.pop_front();
1253 // The code after an 'analyzer_noreturn' call isn't dead, since the call
1254 // can return. The CFG keeps that code as the alternate successor of the
1255 // exit edge, so follow it too.
1256 bool FollowAlternate = P->hasOnlyAnalyzerNoReturnElement();
1257 for (const CFGBlock::AdjacentBlock &Succ : P->succs()) {
1258 const CFGBlock *B = Succ.getReachableBlock();
1259 if (B && ReachableBlocks.insert(Ptr: B).second)
1260 BlockQueue.push_back(x: B);
1261 if (!FollowAlternate)
1262 continue;
1263 const CFGBlock *Alt = Succ.getPossiblyUnreachableBlock();
1264 if (Alt && ReachableBlocks.insert(Ptr: Alt).second)
1265 BlockQueue.push_back(x: Alt);
1266 }
1267 }
1268 }
1269
1270 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1271 bool IsTemplateInstantiation) {
1272 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1273
1274 int UnannotatedCnt = 0;
1275 AnnotatedCnt = 0;
1276
1277 std::deque<const CFGBlock *> BlockQueue(B.pred_begin(), B.pred_end());
1278 while (!BlockQueue.empty()) {
1279 const CFGBlock *P = BlockQueue.front();
1280 BlockQueue.pop_front();
1281 if (!P)
1282 continue;
1283
1284 const Stmt *Term = P->getTerminatorStmt();
1285 if (isa_and_nonnull<SwitchStmt>(Val: Term))
1286 continue; // Switch statement, good.
1287
1288 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(Val: P->getLabel());
1289 if (SW && stripAttributedStmt(S: SW->getSubStmt()) == B.getLabel() &&
1290 P->begin() == P->end())
1291 continue; // Previous case label has no statements, good.
1292
1293 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(Val: P->getLabel());
1294 if (L && stripAttributedStmt(S: L->getSubStmt()) == B.getLabel() &&
1295 P->begin() == P->end())
1296 continue; // Case label is preceded with a normal label, good.
1297
1298 if (!ReachableBlocks.count(Ptr: P)) {
1299 for (const CFGElement &Elem : llvm::reverse(C: *P)) {
1300 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>()) {
1301 if (const AttributedStmt *AS = asFallThroughAttr(S: CS->getStmt())) {
1302 // Don't issue a warning for an unreachable fallthrough
1303 // attribute in template instantiations as it may not be
1304 // unreachable in all instantiations of the template.
1305 if (!IsTemplateInstantiation)
1306 S.Diag(Loc: AS->getBeginLoc(),
1307 DiagID: diag::warn_unreachable_fallthrough_attr);
1308 markFallthroughVisited(Stmt: AS);
1309 ++AnnotatedCnt;
1310 break;
1311 }
1312 // Don't care about other unreachable statements.
1313 }
1314 }
1315 // If there are no unreachable statements, this may be a special
1316 // case in CFG:
1317 // case X: {
1318 // A a; // A has a destructor.
1319 // break;
1320 // }
1321 // // <<<< This place is represented by a 'hanging' CFG block.
1322 // case Y:
1323 continue;
1324 }
1325
1326 const Stmt *LastStmt = getLastStmt(B: *P);
1327 if (const AttributedStmt *AS = asFallThroughAttr(S: LastStmt)) {
1328 markFallthroughVisited(Stmt: AS);
1329 ++AnnotatedCnt;
1330 continue; // Fallthrough annotation, good.
1331 }
1332
1333 if (!LastStmt) { // This block contains no executable statements.
1334 // Traverse its predecessors.
1335 std::copy(first: P->pred_begin(), last: P->pred_end(),
1336 result: std::back_inserter(x&: BlockQueue));
1337 continue;
1338 }
1339
1340 ++UnannotatedCnt;
1341 }
1342 return !!UnannotatedCnt;
1343 }
1344
1345 bool VisitAttributedStmt(AttributedStmt *S) override {
1346 if (asFallThroughAttr(S))
1347 FallthroughStmts.insert(Ptr: S);
1348 return true;
1349 }
1350
1351 bool VisitSwitchStmt(SwitchStmt *S) override {
1352 FoundSwitchStatements = true;
1353 return true;
1354 }
1355
1356 // We don't want to traverse local type declarations. We analyze their
1357 // methods separately.
1358 bool TraverseDecl(Decl *D) override { return true; }
1359
1360 // We analyze lambda bodies separately. Skip them here.
1361 bool TraverseLambdaExpr(LambdaExpr *LE) override {
1362 // Traverse the captures, but not the body.
1363 for (const auto C : zip(t: LE->captures(), u: LE->capture_inits()))
1364 TraverseLambdaCapture(LE, C: &std::get<0>(t: C), Init: std::get<1>(t: C));
1365 return true;
1366 }
1367
1368 private:
1369 static const Stmt *stripAttributedStmt(const Stmt *S) {
1370 if (const auto *AS = dyn_cast_or_null<AttributedStmt>(Val: S)) {
1371 assert(!isa<AttributedStmt>(AS->getSubStmt()));
1372 return AS->getSubStmt();
1373 }
1374 return S;
1375 }
1376
1377 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1378 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(Val: S)) {
1379 if (hasSpecificAttr<FallThroughAttr>(container: AS->getAttrs()))
1380 return AS;
1381 }
1382 return nullptr;
1383 }
1384
1385 static const Stmt *getLastStmt(const CFGBlock &B) {
1386 if (const Stmt *Term = B.getTerminatorStmt())
1387 return Term;
1388 for (const CFGElement &Elem : llvm::reverse(C: B))
1389 if (std::optional<CFGStmt> CS = Elem.getAs<CFGStmt>())
1390 return CS->getStmt();
1391 // Workaround to detect a statement thrown out by CFGBuilder:
1392 // case X: {} case Y:
1393 // case X: ; case Y:
1394 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(Val: B.getLabel()))
1395 if (!isa<SwitchCase>(Val: SW->getSubStmt()))
1396 return SW->getSubStmt();
1397
1398 return nullptr;
1399 }
1400
1401 bool FoundSwitchStatements;
1402 AttrStmts FallthroughStmts;
1403 Sema &S;
1404 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1405};
1406} // anonymous namespace
1407
1408static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1409 SourceLocation Loc) {
1410 TokenValue FallthroughTokens[] = {
1411 tok::l_square, tok::l_square,
1412 PP.getIdentifierInfo(Name: "fallthrough"),
1413 tok::r_square, tok::r_square
1414 };
1415
1416 TokenValue ClangFallthroughTokens[] = {
1417 tok::l_square, tok::l_square, PP.getIdentifierInfo(Name: "clang"),
1418 tok::coloncolon, PP.getIdentifierInfo(Name: "fallthrough"),
1419 tok::r_square, tok::r_square
1420 };
1421
1422 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17 && !PP.getLangOpts().C23;
1423
1424 StringRef MacroName;
1425 if (PreferClangAttr)
1426 MacroName = PP.getLastMacroWithSpelling(Loc, Tokens: ClangFallthroughTokens);
1427 if (MacroName.empty())
1428 MacroName = PP.getLastMacroWithSpelling(Loc, Tokens: FallthroughTokens);
1429 if (MacroName.empty() && !PreferClangAttr)
1430 MacroName = PP.getLastMacroWithSpelling(Loc, Tokens: ClangFallthroughTokens);
1431 if (MacroName.empty()) {
1432 if (!PreferClangAttr)
1433 MacroName = "[[fallthrough]]";
1434 else if (PP.getLangOpts().CPlusPlus)
1435 MacroName = "[[clang::fallthrough]]";
1436 else
1437 MacroName = "__attribute__((fallthrough))";
1438 }
1439 return MacroName;
1440}
1441
1442static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
1443 bool PerFunction) {
1444 FallthroughMapper FM(S);
1445 FM.TraverseStmt(S: AC.getBody());
1446
1447 if (!FM.foundSwitchStatements())
1448 return;
1449
1450 if (PerFunction && FM.getFallthroughStmts().empty())
1451 return;
1452
1453 CFG *Cfg = AC.getCFG();
1454
1455 if (!Cfg)
1456 return;
1457
1458 FM.fillReachableBlocks(Cfg);
1459
1460 for (const CFGBlock *B : llvm::reverse(C&: *Cfg)) {
1461 const Stmt *Label = B->getLabel();
1462
1463 if (!isa_and_nonnull<SwitchCase>(Val: Label))
1464 continue;
1465
1466 int AnnotatedCnt;
1467
1468 bool IsTemplateInstantiation = false;
1469 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: AC.getDecl()))
1470 IsTemplateInstantiation = Function->isTemplateInstantiation();
1471 if (!FM.checkFallThroughIntoBlock(B: *B, AnnotatedCnt,
1472 IsTemplateInstantiation))
1473 continue;
1474
1475 S.Diag(Loc: Label->getBeginLoc(),
1476 DiagID: PerFunction ? diag::warn_unannotated_fallthrough_per_function
1477 : diag::warn_unannotated_fallthrough);
1478
1479 if (!AnnotatedCnt) {
1480 SourceLocation L = Label->getBeginLoc();
1481 if (L.isMacroID())
1482 continue;
1483
1484 const Stmt *Term = B->getTerminatorStmt();
1485 // Skip empty cases.
1486 while (B->empty() && !Term && B->succ_size() == 1) {
1487 B = *B->succ_begin();
1488 Term = B->getTerminatorStmt();
1489 }
1490 if (!(B->empty() && isa_and_nonnull<BreakStmt>(Val: Term))) {
1491 Preprocessor &PP = S.getPreprocessor();
1492 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, Loc: L);
1493 SmallString<64> TextToInsert(AnnotationSpelling);
1494 TextToInsert += "; ";
1495 S.Diag(Loc: L, DiagID: diag::note_insert_fallthrough_fixit)
1496 << AnnotationSpelling
1497 << FixItHint::CreateInsertion(InsertionLoc: L, Code: TextToInsert);
1498 }
1499 S.Diag(Loc: L, DiagID: diag::note_insert_break_fixit)
1500 << FixItHint::CreateInsertion(InsertionLoc: L, Code: "break; ");
1501 }
1502 }
1503
1504 for (const auto *F : FM.getFallthroughStmts())
1505 S.Diag(Loc: F->getBeginLoc(), DiagID: diag::err_fallthrough_attr_invalid_placement);
1506}
1507
1508static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1509 const Stmt *S) {
1510 assert(S);
1511
1512 do {
1513 switch (S->getStmtClass()) {
1514 case Stmt::ForStmtClass:
1515 case Stmt::WhileStmtClass:
1516 case Stmt::CXXForRangeStmtClass:
1517 case Stmt::ObjCForCollectionStmtClass:
1518 return true;
1519 case Stmt::DoStmtClass: {
1520 Expr::EvalResult Result;
1521 if (!cast<DoStmt>(Val: S)->getCond()->EvaluateAsInt(Result, Ctx))
1522 return true;
1523 return Result.Val.getInt().getBoolValue();
1524 }
1525 default:
1526 break;
1527 }
1528 } while ((S = PM.getParent(S)));
1529
1530 return false;
1531}
1532
1533static void diagnoseRepeatedUseOfWeak(Sema &S,
1534 const sema::FunctionScopeInfo *CurFn,
1535 const Decl *D,
1536 const ParentMap &PM) {
1537 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1538 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1539 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
1540 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1541 StmtUsesPair;
1542
1543 ASTContext &Ctx = S.getASTContext();
1544
1545 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1546
1547 // Extract all weak objects that are referenced more than once.
1548 SmallVector<StmtUsesPair, 8> UsesByStmt;
1549 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1550 I != E; ++I) {
1551 const WeakUseVector &Uses = I->second;
1552
1553 // Find the first read of the weak object.
1554 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1555 for ( ; UI != UE; ++UI) {
1556 if (UI->isUnsafe())
1557 break;
1558 }
1559
1560 // If there were only writes to this object, don't warn.
1561 if (UI == UE)
1562 continue;
1563
1564 // If there was only one read, followed by any number of writes, and the
1565 // read is not within a loop, don't warn. Additionally, don't warn in a
1566 // loop if the base object is a local variable -- local variables are often
1567 // changed in loops.
1568 if (UI == Uses.begin()) {
1569 WeakUseVector::const_iterator UI2 = UI;
1570 for (++UI2; UI2 != UE; ++UI2)
1571 if (UI2->isUnsafe())
1572 break;
1573
1574 if (UI2 == UE) {
1575 if (!isInLoop(Ctx, PM, S: UI->getUseExpr()))
1576 continue;
1577
1578 const WeakObjectProfileTy &Profile = I->first;
1579 if (!Profile.isExactProfile())
1580 continue;
1581
1582 const NamedDecl *Base = Profile.getBase();
1583 if (!Base)
1584 Base = Profile.getProperty();
1585 assert(Base && "A profile always has a base or property.");
1586
1587 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Val: Base))
1588 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Val: Base))
1589 continue;
1590 }
1591 }
1592
1593 UsesByStmt.push_back(Elt: StmtUsesPair(UI->getUseExpr(), I));
1594 }
1595
1596 if (UsesByStmt.empty())
1597 return;
1598
1599 // Sort by first use so that we emit the warnings in a deterministic order.
1600 SourceManager &SM = S.getSourceManager();
1601 llvm::sort(C&: UsesByStmt,
1602 Comp: [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1603 return SM.isBeforeInTranslationUnit(LHS: LHS.first->getBeginLoc(),
1604 RHS: RHS.first->getBeginLoc());
1605 });
1606
1607 // Classify the current code body for better warning text.
1608 // This enum should stay in sync with the cases in
1609 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1610 // FIXME: Should we use a common classification enum and the same set of
1611 // possibilities all throughout Sema?
1612 enum {
1613 Function,
1614 Method,
1615 Block,
1616 Lambda
1617 } FunctionKind;
1618
1619 if (isa<sema::BlockScopeInfo>(Val: CurFn))
1620 FunctionKind = Block;
1621 else if (isa<sema::LambdaScopeInfo>(Val: CurFn))
1622 FunctionKind = Lambda;
1623 else if (isa<ObjCMethodDecl>(Val: D))
1624 FunctionKind = Method;
1625 else
1626 FunctionKind = Function;
1627
1628 // Iterate through the sorted problems and emit warnings for each.
1629 for (const auto &P : UsesByStmt) {
1630 const Stmt *FirstRead = P.first;
1631 const WeakObjectProfileTy &Key = P.second->first;
1632 const WeakUseVector &Uses = P.second->second;
1633
1634 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1635 // may not contain enough information to determine that these are different
1636 // properties. We can only be 100% sure of a repeated use in certain cases,
1637 // and we adjust the diagnostic kind accordingly so that the less certain
1638 // case can be turned off if it is too noisy.
1639 unsigned DiagKind;
1640 if (Key.isExactProfile())
1641 DiagKind = diag::warn_arc_repeated_use_of_weak;
1642 else
1643 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1644
1645 // Classify the weak object being accessed for better warning text.
1646 // This enum should stay in sync with the cases in
1647 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1648 enum {
1649 Variable,
1650 Property,
1651 ImplicitProperty,
1652 Ivar
1653 } ObjectKind;
1654
1655 const NamedDecl *KeyProp = Key.getProperty();
1656 if (isa<VarDecl>(Val: KeyProp))
1657 ObjectKind = Variable;
1658 else if (isa<ObjCPropertyDecl>(Val: KeyProp))
1659 ObjectKind = Property;
1660 else if (isa<ObjCMethodDecl>(Val: KeyProp))
1661 ObjectKind = ImplicitProperty;
1662 else if (isa<ObjCIvarDecl>(Val: KeyProp))
1663 ObjectKind = Ivar;
1664 else
1665 llvm_unreachable("Unexpected weak object kind!");
1666
1667 // Do not warn about IBOutlet weak property receivers being set to null
1668 // since they are typically only used from the main thread.
1669 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(Val: KeyProp))
1670 if (Prop->hasAttr<IBOutletAttr>())
1671 continue;
1672
1673 // Show the first time the object was read.
1674 S.Diag(Loc: FirstRead->getBeginLoc(), DiagID: DiagKind)
1675 << int(ObjectKind) << KeyProp << int(FunctionKind)
1676 << FirstRead->getSourceRange();
1677
1678 // Print all the other accesses as notes.
1679 for (const auto &Use : Uses) {
1680 if (Use.getUseExpr() == FirstRead)
1681 continue;
1682 S.Diag(Loc: Use.getUseExpr()->getBeginLoc(),
1683 DiagID: diag::note_arc_weak_also_accessed_here)
1684 << Use.getUseExpr()->getSourceRange();
1685 }
1686 }
1687}
1688
1689namespace clang {
1690namespace {
1691typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
1692typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
1693typedef std::list<DelayedDiag> DiagList;
1694
1695struct SortDiagBySourceLocation {
1696 SourceManager &SM;
1697 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
1698
1699 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1700 // Although this call will be slow, this is only called when outputting
1701 // multiple warnings.
1702 return SM.isBeforeInTranslationUnit(LHS: left.first.first, RHS: right.first.first);
1703 }
1704};
1705} // anonymous namespace
1706} // namespace clang
1707
1708namespace {
1709class UninitValsDiagReporter : public UninitVariablesHandler {
1710 Sema &S;
1711 typedef SmallVector<UninitUse, 2> UsesVec;
1712 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1713 // Prefer using MapVector to DenseMap, so that iteration order will be
1714 // the same as insertion order. This is needed to obtain a deterministic
1715 // order of diagnostics when calling flushDiagnostics().
1716 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1717 UsesMap uses;
1718
1719public:
1720 UninitValsDiagReporter(Sema &S) : S(S) {}
1721 ~UninitValsDiagReporter() override { flushDiagnostics(); }
1722
1723 MappedType &getUses(const VarDecl *vd) {
1724 MappedType &V = uses[vd];
1725 if (!V.getPointer())
1726 V.setPointer(new UsesVec());
1727 return V;
1728 }
1729
1730 void handleUseOfUninitVariable(const VarDecl *vd,
1731 const UninitUse &use) override {
1732 getUses(vd).getPointer()->push_back(Elt: use);
1733 }
1734
1735 void handleSelfInit(const VarDecl *vd) override { getUses(vd).setInt(true); }
1736
1737 void flushDiagnostics() {
1738 for (const auto &P : uses) {
1739 const VarDecl *vd = P.first;
1740 const MappedType &V = P.second;
1741
1742 UsesVec *vec = V.getPointer();
1743 bool hasSelfInit = V.getInt();
1744
1745 diagnoseUnitializedVar(vd, hasSelfInit, vec);
1746
1747 // Release the uses vector.
1748 delete vec;
1749 }
1750
1751 uses.clear();
1752 }
1753
1754private:
1755 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1756 return llvm::any_of(Range: *vec, P: [](const UninitUse &U) {
1757 return U.getKind() == UninitUse::Always ||
1758 U.getKind() == UninitUse::AfterCall ||
1759 U.getKind() == UninitUse::AfterDecl;
1760 });
1761 }
1762
1763 // Print the diagnostic for the variable. We try to warn only on the first
1764 // point at which a variable is used uninitialized. After the first
1765 // diagnostic is printed, further diagnostics for this variable are skipped.
1766 void diagnoseUnitializedVar(const VarDecl *vd, bool hasSelfInit,
1767 UsesVec *vec) {
1768 // Specially handle the case where we have uses of an uninitialized
1769 // variable, but the root cause is an idiomatic self-init. We want
1770 // to report the diagnostic at the self-init since that is the root cause.
1771 if (hasSelfInit && hasAlwaysUninitializedUse(vec)) {
1772 if (DiagnoseUninitializedUse(S, VD: vd,
1773 Use: UninitUse(vd->getInit()->IgnoreParenCasts(),
1774 /*isAlwaysUninit=*/true),
1775 /*alwaysReportSelfInit=*/true))
1776 return;
1777 }
1778
1779 // Sort the uses by their SourceLocations. While not strictly
1780 // guaranteed to produce them in line/column order, this will provide
1781 // a stable ordering.
1782 llvm::sort(C&: *vec, Comp: [](const UninitUse &a, const UninitUse &b) {
1783 // Prefer the direct use of an uninitialized variable over its use via
1784 // constant reference or pointer.
1785 if (a.isConstRefOrPtrUse() != b.isConstRefOrPtrUse())
1786 return b.isConstRefOrPtrUse();
1787 // Prefer a more confident report over a less confident one.
1788 if (a.getKind() != b.getKind())
1789 return a.getKind() > b.getKind();
1790 return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
1791 });
1792
1793 for (const auto &U : *vec) {
1794 if (U.isConstRefUse()) {
1795 if (DiagnoseUninitializedConstRefUse(S, VD: vd, Use: U))
1796 return;
1797 } else if (U.isConstPtrUse()) {
1798 if (DiagnoseUninitializedConstPtrUse(S, VD: vd, Use: U))
1799 return;
1800 } else {
1801 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1802 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
1803 if (DiagnoseUninitializedUse(S, VD: vd, Use))
1804 return;
1805 }
1806 }
1807 }
1808};
1809
1810/// Inter-procedural data for the called-once checker.
1811class CalledOnceInterProceduralData {
1812public:
1813 // Add the delayed warning for the given block.
1814 void addDelayedWarning(const BlockDecl *Block,
1815 PartialDiagnosticAt &&Warning) {
1816 DelayedBlockWarnings[Block].emplace_back(Args: std::move(Warning));
1817 }
1818 // Report all of the warnings we've gathered for the given block.
1819 void flushWarnings(const BlockDecl *Block, Sema &S) {
1820 for (const PartialDiagnosticAt &Delayed : DelayedBlockWarnings[Block])
1821 S.Diag(Loc: Delayed.first, PD: Delayed.second);
1822
1823 discardWarnings(Block);
1824 }
1825 // Discard all of the warnings we've gathered for the given block.
1826 void discardWarnings(const BlockDecl *Block) {
1827 DelayedBlockWarnings.erase(Val: Block);
1828 }
1829
1830private:
1831 using DelayedDiagnostics = SmallVector<PartialDiagnosticAt, 2>;
1832 llvm::DenseMap<const BlockDecl *, DelayedDiagnostics> DelayedBlockWarnings;
1833};
1834
1835class CalledOnceCheckReporter : public CalledOnceCheckHandler {
1836public:
1837 CalledOnceCheckReporter(Sema &S, CalledOnceInterProceduralData &Data)
1838 : S(S), Data(Data) {}
1839 void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call,
1840 const Expr *PrevCall, bool IsCompletionHandler,
1841 bool Poised) override {
1842 auto DiagToReport = IsCompletionHandler
1843 ? diag::warn_completion_handler_called_twice
1844 : diag::warn_called_once_gets_called_twice;
1845 S.Diag(Loc: Call->getBeginLoc(), DiagID: DiagToReport) << Parameter;
1846 S.Diag(Loc: PrevCall->getBeginLoc(), DiagID: diag::note_called_once_gets_called_twice)
1847 << Poised;
1848 }
1849
1850 void handleNeverCalled(const ParmVarDecl *Parameter,
1851 bool IsCompletionHandler) override {
1852 auto DiagToReport = IsCompletionHandler
1853 ? diag::warn_completion_handler_never_called
1854 : diag::warn_called_once_never_called;
1855 S.Diag(Loc: Parameter->getBeginLoc(), DiagID: DiagToReport)
1856 << Parameter << /* Captured */ false;
1857 }
1858
1859 void handleNeverCalled(const ParmVarDecl *Parameter, const Decl *Function,
1860 const Stmt *Where, NeverCalledReason Reason,
1861 bool IsCalledDirectly,
1862 bool IsCompletionHandler) override {
1863 auto DiagToReport = IsCompletionHandler
1864 ? diag::warn_completion_handler_never_called_when
1865 : diag::warn_called_once_never_called_when;
1866 PartialDiagnosticAt Warning(Where->getBeginLoc(), S.PDiag(DiagID: DiagToReport)
1867 << Parameter
1868 << IsCalledDirectly
1869 << (unsigned)Reason);
1870
1871 if (const auto *Block = dyn_cast<BlockDecl>(Val: Function)) {
1872 // We shouldn't report these warnings on blocks immediately
1873 Data.addDelayedWarning(Block, Warning: std::move(Warning));
1874 } else {
1875 S.Diag(Loc: Warning.first, PD: Warning.second);
1876 }
1877 }
1878
1879 void handleCapturedNeverCalled(const ParmVarDecl *Parameter,
1880 const Decl *Where,
1881 bool IsCompletionHandler) override {
1882 auto DiagToReport = IsCompletionHandler
1883 ? diag::warn_completion_handler_never_called
1884 : diag::warn_called_once_never_called;
1885 S.Diag(Loc: Where->getBeginLoc(), DiagID: DiagToReport)
1886 << Parameter << /* Captured */ true;
1887 }
1888
1889 void
1890 handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl *Block) override {
1891 Data.flushWarnings(Block, S);
1892 }
1893
1894 void handleBlockWithNoGuarantees(const BlockDecl *Block) override {
1895 Data.discardWarnings(Block);
1896 }
1897
1898private:
1899 Sema &S;
1900 CalledOnceInterProceduralData &Data;
1901};
1902
1903constexpr unsigned CalledOnceWarnings[] = {
1904 diag::warn_called_once_never_called,
1905 diag::warn_called_once_never_called_when,
1906 diag::warn_called_once_gets_called_twice};
1907
1908constexpr unsigned CompletionHandlerWarnings[]{
1909 diag::warn_completion_handler_never_called,
1910 diag::warn_completion_handler_never_called_when,
1911 diag::warn_completion_handler_called_twice};
1912
1913bool shouldAnalyzeCalledOnceImpl(llvm::ArrayRef<unsigned> DiagIDs,
1914 const DiagnosticsEngine &Diags,
1915 SourceLocation At) {
1916 return llvm::any_of(Range&: DiagIDs, P: [&Diags, At](unsigned DiagID) {
1917 return !Diags.isIgnored(DiagID, Loc: At);
1918 });
1919}
1920
1921bool shouldAnalyzeCalledOnceConventions(const DiagnosticsEngine &Diags,
1922 SourceLocation At) {
1923 return shouldAnalyzeCalledOnceImpl(DiagIDs: CompletionHandlerWarnings, Diags, At);
1924}
1925
1926bool shouldAnalyzeCalledOnceParameters(const DiagnosticsEngine &Diags,
1927 SourceLocation At) {
1928 return shouldAnalyzeCalledOnceImpl(DiagIDs: CalledOnceWarnings, Diags, At) ||
1929 shouldAnalyzeCalledOnceConventions(Diags, At);
1930}
1931} // anonymous namespace
1932
1933//===----------------------------------------------------------------------===//
1934// -Wthread-safety
1935//===----------------------------------------------------------------------===//
1936namespace clang {
1937namespace threadSafety {
1938namespace {
1939class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
1940 Sema &S;
1941 DiagList Warnings;
1942 SourceLocation FunLocation, FunEndLocation;
1943
1944 const FunctionDecl *CurrentFunction;
1945 bool Verbose;
1946
1947 OptionalNotes getNotes() const {
1948 if (Verbose && CurrentFunction) {
1949 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1950 S.PDiag(DiagID: diag::note_thread_warning_in_fun)
1951 << CurrentFunction);
1952 return OptionalNotes(1, FNote);
1953 }
1954 return OptionalNotes();
1955 }
1956
1957 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
1958 OptionalNotes ONS(1, Note);
1959 if (Verbose && CurrentFunction) {
1960 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1961 S.PDiag(DiagID: diag::note_thread_warning_in_fun)
1962 << CurrentFunction);
1963 ONS.push_back(Elt: std::move(FNote));
1964 }
1965 return ONS;
1966 }
1967
1968 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1969 const PartialDiagnosticAt &Note2) const {
1970 OptionalNotes ONS;
1971 ONS.push_back(Elt: Note1);
1972 ONS.push_back(Elt: Note2);
1973 if (Verbose && CurrentFunction) {
1974 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
1975 S.PDiag(DiagID: diag::note_thread_warning_in_fun)
1976 << CurrentFunction);
1977 ONS.push_back(Elt: std::move(FNote));
1978 }
1979 return ONS;
1980 }
1981
1982 OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
1983 return LocLocked.isValid()
1984 ? getNotes(Note: PartialDiagnosticAt(
1985 LocLocked, S.PDiag(DiagID: diag::note_locked_here) << Kind))
1986 : getNotes();
1987 }
1988
1989 OptionalNotes makeUnlockedHereNote(SourceLocation LocUnlocked,
1990 StringRef Kind) {
1991 return LocUnlocked.isValid()
1992 ? getNotes(Note: PartialDiagnosticAt(
1993 LocUnlocked, S.PDiag(DiagID: diag::note_unlocked_here) << Kind))
1994 : getNotes();
1995 }
1996
1997 OptionalNotes makeManagedMismatchNoteForParam(SourceLocation DeclLoc) {
1998 return DeclLoc.isValid()
1999 ? getNotes(Note: PartialDiagnosticAt(
2000 DeclLoc,
2001 S.PDiag(DiagID: diag::note_managed_mismatch_here_for_param)))
2002 : getNotes();
2003 }
2004
2005 public:
2006 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
2007 : S(S), FunLocation(FL), FunEndLocation(FEL),
2008 CurrentFunction(nullptr), Verbose(false) {}
2009
2010 void setVerbose(bool b) { Verbose = b; }
2011
2012 /// Emit all buffered diagnostics in order of sourcelocation.
2013 /// We need to output diagnostics produced while iterating through
2014 /// the lockset in deterministic order, so this function orders diagnostics
2015 /// and outputs them.
2016 void emitDiagnostics() {
2017 Warnings.sort(comp: SortDiagBySourceLocation(S.getSourceManager()));
2018 for (const auto &Diag : Warnings) {
2019 S.Diag(Loc: Diag.first.first, PD: Diag.first.second);
2020 for (const auto &Note : Diag.second)
2021 S.Diag(Loc: Note.first, PD: Note.second);
2022 }
2023 }
2024
2025 void handleUnmatchedUnderlyingMutexes(SourceLocation Loc, SourceLocation DLoc,
2026 Name scopeName, StringRef Kind,
2027 Name expected, Name actual) override {
2028 PartialDiagnosticAt Warning(Loc,
2029 S.PDiag(DiagID: diag::warn_unmatched_underlying_mutexes)
2030 << Kind << scopeName << expected << actual);
2031 Warnings.emplace_back(args: std::move(Warning),
2032 args: makeManagedMismatchNoteForParam(DeclLoc: DLoc));
2033 }
2034
2035 void handleExpectMoreUnderlyingMutexes(SourceLocation Loc,
2036 SourceLocation DLoc, Name scopeName,
2037 StringRef Kind,
2038 Name expected) override {
2039 PartialDiagnosticAt Warning(
2040 Loc, S.PDiag(DiagID: diag::warn_expect_more_underlying_mutexes)
2041 << Kind << scopeName << expected);
2042 Warnings.emplace_back(args: std::move(Warning),
2043 args: makeManagedMismatchNoteForParam(DeclLoc: DLoc));
2044 }
2045
2046 void handleExpectFewerUnderlyingMutexes(SourceLocation Loc,
2047 SourceLocation DLoc, Name scopeName,
2048 StringRef Kind,
2049 Name actual) override {
2050 PartialDiagnosticAt Warning(
2051 Loc, S.PDiag(DiagID: diag::warn_expect_fewer_underlying_mutexes)
2052 << Kind << scopeName << actual);
2053 Warnings.emplace_back(args: std::move(Warning),
2054 args: makeManagedMismatchNoteForParam(DeclLoc: DLoc));
2055 }
2056
2057 void handleInvalidLockExp(SourceLocation Loc) override {
2058 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_cannot_resolve_lock)
2059 << Loc);
2060 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2061 }
2062
2063 void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc,
2064 SourceLocation LocPreviousUnlock) override {
2065 if (Loc.isInvalid())
2066 Loc = FunLocation;
2067 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_unlock_but_no_lock)
2068 << Kind << LockName);
2069 Warnings.emplace_back(args: std::move(Warning),
2070 args: makeUnlockedHereNote(LocUnlocked: LocPreviousUnlock, Kind));
2071 }
2072
2073 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
2074 LockKind Expected, LockKind Received,
2075 SourceLocation LocLocked,
2076 SourceLocation LocUnlock) override {
2077 if (LocUnlock.isInvalid())
2078 LocUnlock = FunLocation;
2079 PartialDiagnosticAt Warning(
2080 LocUnlock, S.PDiag(DiagID: diag::warn_unlock_kind_mismatch)
2081 << Kind << LockName << Received << Expected);
2082 Warnings.emplace_back(args: std::move(Warning),
2083 args: makeLockedHereNote(LocLocked, Kind));
2084 }
2085
2086 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
2087 SourceLocation LocDoubleLock) override {
2088 if (LocDoubleLock.isInvalid())
2089 LocDoubleLock = FunLocation;
2090 PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(DiagID: diag::warn_double_lock)
2091 << Kind << LockName);
2092 Warnings.emplace_back(args: std::move(Warning),
2093 args: makeLockedHereNote(LocLocked, Kind));
2094 }
2095
2096 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
2097 SourceLocation LocLocked,
2098 SourceLocation LocEndOfScope,
2099 LockErrorKind LEK,
2100 bool ReentrancyMismatch) override {
2101 unsigned DiagID = 0;
2102 switch (LEK) {
2103 case LEK_LockedSomePredecessors:
2104 DiagID = diag::warn_lock_some_predecessors;
2105 break;
2106 case LEK_LockedSomeLoopIterations:
2107 DiagID = diag::warn_expecting_lock_held_on_loop;
2108 break;
2109 case LEK_LockedAtEndOfFunction:
2110 DiagID = diag::warn_no_unlock;
2111 break;
2112 case LEK_NotLockedAtEndOfFunction:
2113 DiagID = diag::warn_expecting_locked;
2114 break;
2115 }
2116 if (LocEndOfScope.isInvalid())
2117 LocEndOfScope = FunEndLocation;
2118
2119 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID)
2120 << Kind << LockName
2121 << ReentrancyMismatch);
2122 Warnings.emplace_back(args: std::move(Warning),
2123 args: makeLockedHereNote(LocLocked, Kind));
2124 }
2125
2126 void handleExclusiveAndShared(StringRef Kind, Name LockName,
2127 SourceLocation Loc1,
2128 SourceLocation Loc2) override {
2129 PartialDiagnosticAt Warning(Loc1,
2130 S.PDiag(DiagID: diag::warn_lock_exclusive_and_shared)
2131 << Kind << LockName);
2132 PartialDiagnosticAt Note(Loc2, S.PDiag(DiagID: diag::note_lock_exclusive_and_shared)
2133 << Kind << LockName);
2134 Warnings.emplace_back(args: std::move(Warning), args: getNotes(Note));
2135 }
2136
2137 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
2138 AccessKind AK, SourceLocation Loc) override {
2139 unsigned DiagID = 0;
2140 switch (POK) {
2141 case POK_VarAccess:
2142 case POK_PassByRef:
2143 case POK_ReturnByRef:
2144 case POK_PassPointer:
2145 case POK_ReturnPointer:
2146 DiagID = diag::warn_variable_requires_any_lock;
2147 break;
2148 case POK_VarDereference:
2149 case POK_PtPassByRef:
2150 case POK_PtReturnByRef:
2151 case POK_PtPassPointer:
2152 case POK_PtReturnPointer:
2153 DiagID = diag::warn_var_deref_requires_any_lock;
2154 break;
2155 case POK_FunctionCall:
2156 llvm_unreachable("Only works for variables");
2157 break;
2158 }
2159 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
2160 << D << getLockKindFromAccessKind(AK));
2161 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2162 }
2163
2164 void handleGuardedByAnyReadNotHeld(const NamedDecl *D,
2165 ProtectedOperationKind POK,
2166 ArrayRef<StringRef> LockNames,
2167 SourceLocation Loc) override {
2168 bool IsDeref;
2169 switch (POK) {
2170 case POK_VarAccess:
2171 case POK_PassByRef:
2172 case POK_ReturnByRef:
2173 case POK_PassPointer:
2174 case POK_ReturnPointer:
2175 IsDeref = false;
2176 break;
2177 case POK_VarDereference:
2178 case POK_PtPassByRef:
2179 case POK_PtReturnByRef:
2180 case POK_PtPassPointer:
2181 case POK_PtReturnPointer:
2182 IsDeref = true;
2183 break;
2184 case POK_FunctionCall:
2185 llvm_unreachable("POK_FunctionCall not applicable here");
2186 }
2187 std::string Quoted;
2188 llvm::raw_string_ostream OS(Quoted);
2189 llvm::ListSeparator LS;
2190 for (StringRef Name : LockNames)
2191 OS << LS << "'" << Name << "'";
2192 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_requires_any_of_locks)
2193 << D << IsDeref << Quoted);
2194 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2195 }
2196
2197 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
2198 ProtectedOperationKind POK, Name LockName,
2199 LockKind LK, SourceLocation Loc,
2200 Name *PossibleMatch) override {
2201 unsigned DiagID = 0;
2202 if (PossibleMatch) {
2203 switch (POK) {
2204 case POK_VarAccess:
2205 DiagID = diag::warn_variable_requires_lock_precise;
2206 break;
2207 case POK_VarDereference:
2208 DiagID = diag::warn_var_deref_requires_lock_precise;
2209 break;
2210 case POK_FunctionCall:
2211 DiagID = diag::warn_fun_requires_lock_precise;
2212 break;
2213 case POK_PassByRef:
2214 DiagID = diag::warn_guarded_pass_by_reference;
2215 break;
2216 case POK_PtPassByRef:
2217 DiagID = diag::warn_pt_guarded_pass_by_reference;
2218 break;
2219 case POK_ReturnByRef:
2220 DiagID = diag::warn_guarded_return_by_reference;
2221 break;
2222 case POK_PtReturnByRef:
2223 DiagID = diag::warn_pt_guarded_return_by_reference;
2224 break;
2225 case POK_PassPointer:
2226 DiagID = diag::warn_guarded_pass_pointer;
2227 break;
2228 case POK_PtPassPointer:
2229 DiagID = diag::warn_pt_guarded_pass_pointer;
2230 break;
2231 case POK_ReturnPointer:
2232 DiagID = diag::warn_guarded_return_pointer;
2233 break;
2234 case POK_PtReturnPointer:
2235 DiagID = diag::warn_pt_guarded_return_pointer;
2236 break;
2237 }
2238 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
2239 << D
2240 << LockName << LK);
2241 PartialDiagnosticAt Note(Loc, S.PDiag(DiagID: diag::note_found_mutex_near_match)
2242 << *PossibleMatch);
2243 if (Verbose && POK == POK_VarAccess) {
2244 PartialDiagnosticAt VNote(D->getLocation(),
2245 S.PDiag(DiagID: diag::note_guarded_by_declared_here)
2246 << D->getDeclName());
2247 Warnings.emplace_back(args: std::move(Warning), args: getNotes(Note1: Note, Note2: VNote));
2248 } else
2249 Warnings.emplace_back(args: std::move(Warning), args: getNotes(Note));
2250 } else {
2251 switch (POK) {
2252 case POK_VarAccess:
2253 DiagID = diag::warn_variable_requires_lock;
2254 break;
2255 case POK_VarDereference:
2256 DiagID = diag::warn_var_deref_requires_lock;
2257 break;
2258 case POK_FunctionCall:
2259 DiagID = diag::warn_fun_requires_lock;
2260 break;
2261 case POK_PassByRef:
2262 DiagID = diag::warn_guarded_pass_by_reference;
2263 break;
2264 case POK_PtPassByRef:
2265 DiagID = diag::warn_pt_guarded_pass_by_reference;
2266 break;
2267 case POK_ReturnByRef:
2268 DiagID = diag::warn_guarded_return_by_reference;
2269 break;
2270 case POK_PtReturnByRef:
2271 DiagID = diag::warn_pt_guarded_return_by_reference;
2272 break;
2273 case POK_PassPointer:
2274 DiagID = diag::warn_guarded_pass_pointer;
2275 break;
2276 case POK_PtPassPointer:
2277 DiagID = diag::warn_pt_guarded_pass_pointer;
2278 break;
2279 case POK_ReturnPointer:
2280 DiagID = diag::warn_guarded_return_pointer;
2281 break;
2282 case POK_PtReturnPointer:
2283 DiagID = diag::warn_pt_guarded_return_pointer;
2284 break;
2285 }
2286 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
2287 << D
2288 << LockName << LK);
2289 if (Verbose && POK == POK_VarAccess) {
2290 PartialDiagnosticAt Note(D->getLocation(),
2291 S.PDiag(DiagID: diag::note_guarded_by_declared_here));
2292 Warnings.emplace_back(args: std::move(Warning), args: getNotes(Note));
2293 } else
2294 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2295 }
2296 }
2297
2298 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
2299 SourceLocation Loc) override {
2300 PartialDiagnosticAt Warning(Loc,
2301 S.PDiag(DiagID: diag::warn_acquire_requires_negative_cap)
2302 << Kind << LockName << Neg);
2303 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2304 }
2305
2306 void handleNegativeNotHeld(const NamedDecl *D, Name LockName,
2307 SourceLocation Loc) override {
2308 PartialDiagnosticAt Warning(
2309 Loc, S.PDiag(DiagID: diag::warn_fun_requires_negative_cap) << D << LockName);
2310 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2311 }
2312
2313 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
2314 SourceLocation Loc) override {
2315 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_fun_excludes_mutex)
2316 << Kind << FunName << LockName);
2317 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2318 }
2319
2320 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
2321 SourceLocation Loc) override {
2322 PartialDiagnosticAt Warning(Loc,
2323 S.PDiag(DiagID: diag::warn_acquired_before) << Kind << L1Name << L2Name);
2324 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2325 }
2326
2327 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
2328 PartialDiagnosticAt Warning(Loc,
2329 S.PDiag(DiagID: diag::warn_acquired_before_after_cycle) << L1Name);
2330 Warnings.emplace_back(args: std::move(Warning), args: getNotes());
2331 }
2332
2333 void enterFunction(const FunctionDecl* FD) override {
2334 CurrentFunction = FD;
2335 }
2336
2337 void leaveFunction(const FunctionDecl* FD) override {
2338 CurrentFunction = nullptr;
2339 }
2340};
2341} // anonymous namespace
2342} // namespace threadSafety
2343} // namespace clang
2344
2345//===----------------------------------------------------------------------===//
2346// -Wconsumed
2347//===----------------------------------------------------------------------===//
2348
2349namespace clang {
2350namespace consumed {
2351namespace {
2352class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
2353
2354 Sema &S;
2355 DiagList Warnings;
2356
2357public:
2358
2359 ConsumedWarningsHandler(Sema &S) : S(S) {}
2360
2361 void emitDiagnostics() override {
2362 Warnings.sort(comp: SortDiagBySourceLocation(S.getSourceManager()));
2363 for (const auto &Diag : Warnings) {
2364 S.Diag(Loc: Diag.first.first, PD: Diag.first.second);
2365 for (const auto &Note : Diag.second)
2366 S.Diag(Loc: Note.first, PD: Note.second);
2367 }
2368 }
2369
2370 void warnLoopStateMismatch(SourceLocation Loc,
2371 StringRef VariableName) override {
2372 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_loop_state_mismatch) <<
2373 VariableName);
2374
2375 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2376 }
2377
2378 void warnParamReturnTypestateMismatch(SourceLocation Loc,
2379 StringRef VariableName,
2380 StringRef ExpectedState,
2381 StringRef ObservedState) override {
2382
2383 PartialDiagnosticAt Warning(Loc, S.PDiag(
2384 DiagID: diag::warn_param_return_typestate_mismatch) << VariableName <<
2385 ExpectedState << ObservedState);
2386
2387 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2388 }
2389
2390 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
2391 StringRef ObservedState) override {
2392
2393 PartialDiagnosticAt Warning(Loc, S.PDiag(
2394 DiagID: diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
2395
2396 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2397 }
2398
2399 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
2400 StringRef TypeName) override {
2401 PartialDiagnosticAt Warning(Loc, S.PDiag(
2402 DiagID: diag::warn_return_typestate_for_unconsumable_type) << TypeName);
2403
2404 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2405 }
2406
2407 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
2408 StringRef ObservedState) override {
2409
2410 PartialDiagnosticAt Warning(Loc, S.PDiag(
2411 DiagID: diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
2412
2413 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2414 }
2415
2416 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
2417 SourceLocation Loc) override {
2418
2419 PartialDiagnosticAt Warning(Loc, S.PDiag(
2420 DiagID: diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
2421
2422 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2423 }
2424
2425 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
2426 StringRef State, SourceLocation Loc) override {
2427
2428 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID: diag::warn_use_in_invalid_state) <<
2429 MethodName << VariableName << State);
2430
2431 Warnings.emplace_back(args: std::move(Warning), args: OptionalNotes());
2432 }
2433};
2434} // anonymous namespace
2435} // namespace consumed
2436} // namespace clang
2437
2438//===----------------------------------------------------------------------===//
2439// Unsafe buffer usage analysis.
2440//===----------------------------------------------------------------------===//
2441
2442namespace {
2443
2444bool isMainParam(const Decl *D) {
2445 if (const auto *PVD = dyn_cast_or_null<ParmVarDecl>(Val: D))
2446 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PVD->getDeclContext()))
2447 return FD->isMain();
2448 return false;
2449}
2450
2451bool refersMainParam(const Expr *E) {
2452 if (!E)
2453 return false;
2454 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
2455 return isMainParam(D: DRE->getDecl());
2456 return false;
2457}
2458
2459// The base diagnostic comes first, so that the common case of checking whether
2460// all of them are ignored needs one lookup.
2461static constexpr unsigned UnsafeLibcCallDiagIDs[] = {
2462 diag::warn_unsafe_buffer_libc_call,
2463 diag::warn_unsafe_buffer_libc_call_numeric_conversion,
2464 diag::warn_unsafe_buffer_libc_call_string_manipulation,
2465 diag::warn_unsafe_buffer_libc_call_string_examination,
2466 diag::warn_unsafe_buffer_libc_call_memory,
2467 diag::warn_unsafe_buffer_libc_call_io,
2468 diag::warn_unsafe_buffer_libc_call_printf,
2469 diag::warn_unsafe_buffer_libc_call_scanf,
2470};
2471
2472static unsigned getUnsafeLibcCallDiagID(UnsafeLibcFunctionFamily Family) {
2473 switch (Family) {
2474 case UnsafeLibcFunctionFamily::Other:
2475 return diag::warn_unsafe_buffer_libc_call;
2476 case UnsafeLibcFunctionFamily::NumericConversion:
2477 return diag::warn_unsafe_buffer_libc_call_numeric_conversion;
2478 case UnsafeLibcFunctionFamily::StringManipulation:
2479 return diag::warn_unsafe_buffer_libc_call_string_manipulation;
2480 case UnsafeLibcFunctionFamily::StringExamination:
2481 return diag::warn_unsafe_buffer_libc_call_string_examination;
2482 case UnsafeLibcFunctionFamily::Memory:
2483 return diag::warn_unsafe_buffer_libc_call_memory;
2484 case UnsafeLibcFunctionFamily::IO:
2485 return diag::warn_unsafe_buffer_libc_call_io;
2486 case UnsafeLibcFunctionFamily::Printf:
2487 return diag::warn_unsafe_buffer_libc_call_printf;
2488 case UnsafeLibcFunctionFamily::Scanf:
2489 return diag::warn_unsafe_buffer_libc_call_scanf;
2490 }
2491 llvm_unreachable("unknown UnsafeLibcFunctionFamily");
2492}
2493
2494class UnsafeBufferUsageReporter : public UnsafeBufferUsageHandler {
2495 Sema &S;
2496 bool SuggestSuggestions; // Recommend -fsafe-buffer-usage-suggestions?
2497
2498 // Lists as a string the names of variables in `VarGroupForVD` except for `VD`
2499 // itself:
2500 std::string listVariableGroupAsString(
2501 const VarDecl *VD, const ArrayRef<const VarDecl *> &VarGroupForVD) const {
2502 if (VarGroupForVD.size() <= 1)
2503 return "";
2504
2505 std::vector<StringRef> VarNames;
2506 auto PutInQuotes = [](StringRef S) -> std::string {
2507 return "'" + S.str() + "'";
2508 };
2509
2510 for (auto *V : VarGroupForVD) {
2511 if (V == VD)
2512 continue;
2513 VarNames.push_back(x: V->getName());
2514 }
2515 if (VarNames.size() == 1) {
2516 return PutInQuotes(VarNames[0]);
2517 }
2518 if (VarNames.size() == 2) {
2519 return PutInQuotes(VarNames[0]) + " and " + PutInQuotes(VarNames[1]);
2520 }
2521 assert(VarGroupForVD.size() > 3);
2522 const unsigned N = VarNames.size() -
2523 2; // need to print the last two names as "..., X, and Y"
2524 std::string AllVars = "";
2525
2526 for (unsigned I = 0; I < N; ++I)
2527 AllVars.append(str: PutInQuotes(VarNames[I]) + ", ");
2528 AllVars.append(str: PutInQuotes(VarNames[N]) + ", and " +
2529 PutInQuotes(VarNames[N + 1]));
2530 return AllVars;
2531 }
2532
2533public:
2534 UnsafeBufferUsageReporter(Sema &S, bool SuggestSuggestions)
2535 : S(S), SuggestSuggestions(SuggestSuggestions) {}
2536
2537 void handleUnsafeOperation(const Stmt *Operation, bool IsRelatedToDecl,
2538 ASTContext &Ctx) override {
2539 SourceLocation Loc;
2540 SourceRange Range;
2541 unsigned MsgParam = 0;
2542 NamedDecl *D = nullptr;
2543 const Expr *BufferOperand = nullptr;
2544 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: Operation)) {
2545 BufferOperand = ASE->getBase();
2546 Loc = BufferOperand->getExprLoc();
2547 Range = BufferOperand->getSourceRange();
2548 MsgParam = 2;
2549 } else if (const auto *BO = dyn_cast<BinaryOperator>(Val: Operation)) {
2550 BinaryOperator::Opcode Op = BO->getOpcode();
2551 if (Op == BO_Add || Op == BO_AddAssign || Op == BO_Sub ||
2552 Op == BO_SubAssign) {
2553 if (BO->getRHS()->getType()->isIntegerType()) {
2554 BufferOperand = BO->getLHS();
2555 Loc = BufferOperand->getExprLoc();
2556 Range = BufferOperand->getSourceRange();
2557 } else {
2558 BufferOperand = BO->getRHS();
2559 Loc = BufferOperand->getExprLoc();
2560 Range = BufferOperand->getSourceRange();
2561 }
2562 MsgParam = 1;
2563 }
2564 } else if (const auto *UO = dyn_cast<UnaryOperator>(Val: Operation)) {
2565 UnaryOperator::Opcode Op = UO->getOpcode();
2566 if (Op == UO_PreInc || Op == UO_PreDec || Op == UO_PostInc ||
2567 Op == UO_PostDec) {
2568 BufferOperand = UO->getSubExpr();
2569 Loc = BufferOperand->getExprLoc();
2570 Range = BufferOperand->getSourceRange();
2571 MsgParam = 1;
2572 }
2573 } else {
2574 if (isa<CallExpr>(Val: Operation) || isa<CXXConstructExpr>(Val: Operation)) {
2575 // note_unsafe_buffer_operation doesn't have this mode yet.
2576 assert(!IsRelatedToDecl && "Not implemented yet!");
2577 MsgParam = 3;
2578 } else if (isa<MemberExpr>(Val: Operation)) {
2579 // note_unsafe_buffer_operation doesn't have this mode yet.
2580 assert(!IsRelatedToDecl && "Not implemented yet!");
2581 auto *ME = cast<MemberExpr>(Val: Operation);
2582 D = ME->getMemberDecl();
2583 MsgParam = 5;
2584 } else if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Val: Operation)) {
2585 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(
2586 Val: ECE->getSubExpr()->IgnoreParens())) {
2587 D = CE->getMethodDecl();
2588 }
2589
2590 if (!D)
2591 return;
2592
2593 MsgParam = 4;
2594 }
2595 Loc = Operation->getBeginLoc();
2596 Range = Operation->getSourceRange();
2597 }
2598 if (IsRelatedToDecl) {
2599 assert(!SuggestSuggestions &&
2600 "Variables blamed for unsafe buffer usage without suggestions!");
2601 S.Diag(Loc, DiagID: diag::note_unsafe_buffer_operation) << MsgParam << Range;
2602 } else {
2603 unsigned DiagID = refersMainParam(E: BufferOperand)
2604 ? diag::warn_unsafe_buffer_operation_main_argv
2605 : diag::warn_unsafe_buffer_operation;
2606
2607 if (D)
2608 S.Diag(Loc, DiagID) << MsgParam << D << Range;
2609 else
2610 S.Diag(Loc, DiagID) << MsgParam << Range;
2611 if (SuggestSuggestions) {
2612 S.Diag(Loc, DiagID: diag::note_safe_buffer_usage_suggestions_disabled);
2613 }
2614 }
2615 }
2616
2617 void handleUnsafeLibcCall(const CallExpr *Call, unsigned PrintfInfo,
2618 UnsafeLibcFunctionFamily Family, ASTContext &Ctx,
2619 const Expr *UnsafeArg = nullptr) override {
2620 unsigned DiagID = getUnsafeLibcCallDiagID(Family);
2621 if (PrintfInfo & 0x8) {
2622 // The callee is a function with the format attribute. See the
2623 // documentation of PrintfInfo in UnsafeBufferUsageHandler, and
2624 // UnsafeLibcFunctionCallGadget::UnsafeKind.
2625 DiagID = diag::warn_unsafe_buffer_format_attr_call;
2626 PrintfInfo ^= 0x8;
2627 }
2628 S.Diag(Loc: Call->getBeginLoc(), DiagID)
2629 << Call->getDirectCallee() // We've checked there is a direct callee
2630 << Call->getSourceRange();
2631 if (PrintfInfo > 0) {
2632 SourceRange R =
2633 UnsafeArg ? UnsafeArg->getSourceRange() : Call->getSourceRange();
2634 S.Diag(Loc: R.getBegin(), DiagID: diag::note_unsafe_buffer_printf_call)
2635 << PrintfInfo << R;
2636 }
2637 }
2638
2639 void handleUnsafeOperationInContainer(const Stmt *Operation,
2640 bool IsRelatedToDecl,
2641 ASTContext &Ctx) override {
2642 SourceLocation Loc;
2643 SourceRange Range;
2644 unsigned MsgParam = 0;
2645 std::string ContainerName = "container";
2646
2647 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(Val: Operation)) {
2648 Loc = CtorExpr->getLocation();
2649 Range = CtorExpr->getSourceRange();
2650 if (auto *TD = CtorExpr->getConstructor()->getParent()) {
2651 ContainerName = TD->getQualifiedNameAsString();
2652 }
2653 } else if (const auto *Call = dyn_cast<CallExpr>(Val: Operation)) {
2654 Loc = Call->getExprLoc();
2655 Range = Call->getSourceRange();
2656 if (const auto *FD = Call->getDirectCallee()) {
2657 ContainerName = FD->getQualifiedNameAsString();
2658 }
2659 } else {
2660 Loc = Operation->getBeginLoc();
2661 Range = Operation->getSourceRange();
2662 }
2663
2664 // Pass the container name to fill the %0 parameter
2665 S.Diag(Loc, DiagID: diag::warn_unsafe_buffer_usage_in_container) << ContainerName;
2666
2667 if (IsRelatedToDecl) {
2668 assert(!SuggestSuggestions &&
2669 "Variables blamed for unsafe buffer usage without suggestions!");
2670 S.Diag(Loc, DiagID: diag::note_unsafe_buffer_operation) << MsgParam << Range;
2671 }
2672 }
2673
2674 void handleUnsafeOperationInStringView(const Stmt *Operation,
2675 bool IsRelatedToDecl,
2676 ASTContext &Ctx) override {
2677 // Extracting location: prioritize the specific location of the constructor
2678 SourceLocation Loc = Operation->getBeginLoc();
2679 SourceRange Range = Operation->getSourceRange();
2680
2681 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(Val: Operation)) {
2682 Loc = CtorExpr->getLocation();
2683 }
2684
2685 // 1. Emit the primary warning for string_view
2686 S.Diag(Loc, DiagID: diag::warn_unsafe_buffer_usage_in_container)
2687 << "std::string_view";
2688
2689 // 2. If a specific variable is 'blamed', emit the note
2690 if (IsRelatedToDecl) {
2691 // MsgParam 0 is "unsafe operation"
2692 // Range helps the IDE underline the whole expression
2693 S.Diag(Loc, DiagID: diag::note_unsafe_buffer_operation) << 0 << Range;
2694 }
2695 }
2696
2697 void handleUnsafeVariableGroup(const VarDecl *Variable,
2698 const VariableGroupsManager &VarGrpMgr,
2699 FixItList &&Fixes, const Decl *D,
2700 const FixitStrategy &VarTargetTypes) override {
2701 assert(!SuggestSuggestions &&
2702 "Unsafe buffer usage fixits displayed without suggestions!");
2703
2704 unsigned DiagID = isMainParam(D: Variable)
2705 ? diag::warn_unsafe_buffer_variable_main_argv
2706 : diag::warn_unsafe_buffer_variable;
2707
2708 S.Diag(Loc: Variable->getLocation(), DiagID)
2709 << Variable << (Variable->getType()->isPointerType() ? 0 : 1)
2710 << Variable->getSourceRange();
2711 if (!Fixes.empty()) {
2712 assert(isa<NamedDecl>(D) &&
2713 "Fix-its are generated only for `NamedDecl`s");
2714 const NamedDecl *ND = cast<NamedDecl>(Val: D);
2715 bool BriefMsg = false;
2716 // If the variable group involves parameters, the diagnostic message will
2717 // NOT explain how the variables are grouped as the reason is non-trivial
2718 // and irrelavant to users' experience:
2719 const auto VarGroupForVD = VarGrpMgr.getGroupOfVar(Var: Variable, HasParm: &BriefMsg);
2720 unsigned FixItStrategy = 0;
2721 switch (VarTargetTypes.lookup(VD: Variable)) {
2722 case clang::FixitStrategy::Kind::Span:
2723 FixItStrategy = 0;
2724 break;
2725 case clang::FixitStrategy::Kind::Array:
2726 FixItStrategy = 1;
2727 break;
2728 default:
2729 assert(false && "We support only std::span and std::array");
2730 };
2731
2732 const auto &FD =
2733 S.Diag(Loc: Variable->getLocation(),
2734 DiagID: BriefMsg ? diag::note_unsafe_buffer_variable_fixit_together
2735 : diag::note_unsafe_buffer_variable_fixit_group);
2736
2737 FD << Variable << FixItStrategy;
2738 FD << listVariableGroupAsString(VD: Variable, VarGroupForVD)
2739 << (VarGroupForVD.size() > 1) << ND;
2740 for (const auto &F : Fixes) {
2741 FD << F;
2742 }
2743 }
2744
2745#ifndef NDEBUG
2746 if (areDebugNotesRequested())
2747 for (const DebugNote &Note: DebugNotesByVar[Variable])
2748 S.Diag(Note.first, diag::note_safe_buffer_debug_mode) << Note.second;
2749#endif
2750 }
2751
2752 void handleUnsafeUniquePtrArrayAccess(const DynTypedNode &Node,
2753 bool IsRelatedToDecl,
2754 ASTContext &Ctx) override {
2755 SourceLocation Loc;
2756
2757 Loc = Node.get<Stmt>()->getBeginLoc();
2758 S.Diag(Loc, DiagID: diag::warn_unsafe_buffer_usage_unique_ptr_array_access)
2759 << Node.getSourceRange();
2760 }
2761
2762 bool isSafeBufferOptOut(const SourceLocation &Loc) const override {
2763 return S.PP.isSafeBufferOptOut(SourceMgr: S.getSourceManager(), Loc);
2764 }
2765
2766 bool ignoreUnsafeBufferInContainer(const SourceLocation &Loc) const override {
2767 return S.Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_usage_in_container, Loc);
2768 }
2769
2770 bool ignoreUnsafeBufferInLibcCall(const SourceLocation &Loc) const override {
2771 return llvm::all_of(Range: UnsafeLibcCallDiagIDs, P: [&](unsigned ID) {
2772 return S.Diags.isIgnored(DiagID: ID, Loc);
2773 });
2774 }
2775
2776 bool
2777 ignoreUnsafeBufferInFormatAttrCall(const SourceLocation &Loc) const override {
2778 return S.Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_format_attr_call, Loc);
2779 }
2780
2781 bool ignoreUnsafeBufferInStaticSizedArray(
2782 const SourceLocation &Loc) const override {
2783 return S.Diags.isIgnored(
2784 DiagID: diag::warn_unsafe_buffer_usage_in_static_sized_array, Loc);
2785 }
2786
2787 // Returns the text representation of clang::unsafe_buffer_usage attribute.
2788 // `WSSuffix` holds customized "white-space"s, e.g., newline or whilespace
2789 // characters.
2790 std::string
2791 getUnsafeBufferUsageAttributeTextAt(SourceLocation Loc,
2792 StringRef WSSuffix = "") const override {
2793 Preprocessor &PP = S.getPreprocessor();
2794 TokenValue ClangUnsafeBufferUsageTokens[] = {
2795 tok::l_square,
2796 tok::l_square,
2797 PP.getIdentifierInfo(Name: "clang"),
2798 tok::coloncolon,
2799 PP.getIdentifierInfo(Name: "unsafe_buffer_usage"),
2800 tok::r_square,
2801 tok::r_square};
2802
2803 StringRef MacroName;
2804
2805 // The returned macro (it returns) is guaranteed not to be function-like:
2806 MacroName = PP.getLastMacroWithSpelling(Loc, Tokens: ClangUnsafeBufferUsageTokens);
2807 if (MacroName.empty())
2808 MacroName = "[[clang::unsafe_buffer_usage]]";
2809 return MacroName.str() + WSSuffix.str();
2810 }
2811};
2812} // namespace
2813
2814//===----------------------------------------------------------------------===//
2815// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2816// warnings on a function, method, or block.
2817//===----------------------------------------------------------------------===//
2818
2819sema::AnalysisBasedWarnings::Policy::Policy() {
2820 enableCheckFallThrough = 1;
2821 enableCheckUnreachable = 0;
2822 enableThreadSafetyAnalysis = 0;
2823 enableConsumedAnalysis = 0;
2824}
2825
2826/// InterProceduralData aims to be a storage of whatever data should be passed
2827/// between analyses of different functions.
2828///
2829/// At the moment, its primary goal is to make the information gathered during
2830/// the analysis of the blocks available during the analysis of the enclosing
2831/// function. This is important due to the fact that blocks are analyzed before
2832/// the enclosed function is even parsed fully, so it is not viable to access
2833/// anything in the outer scope while analyzing the block. On the other hand,
2834/// re-building CFG for blocks and re-analyzing them when we do have all the
2835/// information (i.e. during the analysis of the enclosing function) seems to be
2836/// ill-designed.
2837class sema::AnalysisBasedWarnings::InterProceduralData {
2838public:
2839 // It is important to analyze blocks within functions because it's a very
2840 // common pattern to capture completion handler parameters by blocks.
2841 CalledOnceInterProceduralData CalledOnceData;
2842};
2843
2844template <typename... Ts>
2845static bool areAnyEnabled(DiagnosticsEngine &D, SourceLocation Loc,
2846 Ts... Diags) {
2847 return (!D.isIgnored(DiagID: Diags, Loc) || ...);
2848}
2849
2850sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2851 : S(s), IPData(std::make_unique<InterProceduralData>()),
2852 NumFunctionsAnalyzed(0), NumFunctionsWithBadCFGs(0), NumCFGBlocks(0),
2853 MaxCFGBlocksPerFunction(0), NumUninitAnalysisFunctions(0),
2854 NumUninitAnalysisVariables(0), MaxUninitAnalysisVariablesPerFunction(0),
2855 NumUninitAnalysisBlockVisits(0),
2856 MaxUninitAnalysisBlockVisitsPerFunction(0) {
2857}
2858
2859// We need this here for unique_ptr with forward declared class.
2860sema::AnalysisBasedWarnings::~AnalysisBasedWarnings() = default;
2861
2862sema::AnalysisBasedWarnings::Policy
2863sema::AnalysisBasedWarnings::getPolicyInEffectAt(SourceLocation Loc) {
2864 using namespace diag;
2865 DiagnosticsEngine &D = S.getDiagnostics();
2866
2867 // This runs at the end of every function definition, and the checks below
2868 // resolve Loc against the pragma diagnostic state (and system header/macro
2869 // classification) once per queried diagnostic. Those inputs fully determine
2870 // the result, so cache the policy on them instead (PolicyOverrides are
2871 // transient per-function state and are applied after the cache lookup).
2872 const bool Cacheable = !D.hasDiagSuppressionMapping() && Loc.isValid();
2873 const void *StateKey = nullptr;
2874 unsigned SysIdx = 0;
2875 if (Cacheable) {
2876 StateKey = D.getDiagStateKeyForLoc(Loc);
2877 SysIdx = static_cast<unsigned>(D.getDiagStateSystemClassForLoc(Loc));
2878 auto It = PolicyCache[SysIdx].find(Val: StateKey);
2879 if (It != PolicyCache[SysIdx].end()) {
2880 Policy P = It->second;
2881 P.enableCheckUnreachable |= PolicyOverrides.enableCheckUnreachable;
2882 P.enableThreadSafetyAnalysis |=
2883 PolicyOverrides.enableThreadSafetyAnalysis;
2884 P.enableConsumedAnalysis |= PolicyOverrides.enableConsumedAnalysis;
2885 return P;
2886 }
2887 }
2888
2889 Policy P;
2890
2891 // Note: The enabled checks should be kept in sync with the switch in
2892 // SemaPPCallbacks::PragmaDiagnostic().
2893 P.enableCheckUnreachable =
2894 areAnyEnabled(D, Loc, Diags: warn_unreachable, Diags: warn_unreachable_break,
2895 Diags: warn_unreachable_return, Diags: warn_unreachable_loop_increment);
2896
2897 P.enableThreadSafetyAnalysis = areAnyEnabled(D, Loc, Diags: warn_double_lock);
2898
2899 P.enableConsumedAnalysis = areAnyEnabled(D, Loc, Diags: warn_use_in_invalid_state);
2900
2901 if (Cacheable)
2902 PolicyCache[SysIdx][StateKey] = P;
2903
2904 P.enableCheckUnreachable |= PolicyOverrides.enableCheckUnreachable;
2905 P.enableThreadSafetyAnalysis |= PolicyOverrides.enableThreadSafetyAnalysis;
2906 P.enableConsumedAnalysis |= PolicyOverrides.enableConsumedAnalysis;
2907 return P;
2908}
2909
2910void sema::AnalysisBasedWarnings::clearPolicyCache() {
2911 for (auto &M : PolicyCache)
2912 M.clear();
2913}
2914
2915void sema::AnalysisBasedWarnings::clearOverrides() {
2916 PolicyOverrides.enableCheckUnreachable = false;
2917 PolicyOverrides.enableConsumedAnalysis = false;
2918 PolicyOverrides.enableThreadSafetyAnalysis = false;
2919}
2920
2921static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2922 for (const auto &D : fscope->PossiblyUnreachableDiags)
2923 S.Diag(Loc: D.Loc, PD: D.PD);
2924}
2925
2926template <typename Iterator>
2927static void emitPossiblyUnreachableDiags(Sema &S, AnalysisDeclContext &AC,
2928 std::pair<Iterator, Iterator> PUDs) {
2929
2930 if (PUDs.first == PUDs.second)
2931 return;
2932
2933 for (auto I = PUDs.first; I != PUDs.second; ++I) {
2934 for (const Stmt *S : I->Stmts)
2935 AC.registerForcedBlockExpression(stmt: S);
2936 }
2937
2938 if (AC.getCFG()) {
2939 CFGReverseBlockReachabilityAnalysis *Analysis =
2940 AC.getCFGReachablityAnalysis();
2941
2942 for (auto I = PUDs.first; I != PUDs.second; ++I) {
2943 const auto &D = *I;
2944 if (llvm::all_of(D.Stmts, [&](const Stmt *St) {
2945 const CFGBlock *Block = AC.getBlockForRegisteredExpression(stmt: St);
2946 // FIXME: We should be able to assert that block is non-null, but
2947 // the CFG analysis can skip potentially-evaluated expressions in
2948 // edge cases; see test/Sema/vla-2.c.
2949 if (Block && Analysis)
2950 if (!Analysis->isReachable(Src: &AC.getCFG()->getEntry(), Dst: Block))
2951 return false;
2952 return true;
2953 })) {
2954 S.Diag(D.Loc, D.PD);
2955 }
2956 }
2957 } else {
2958 for (auto I = PUDs.first; I != PUDs.second; ++I)
2959 S.Diag(I->Loc, I->PD);
2960 }
2961}
2962
2963void sema::AnalysisBasedWarnings::registerVarDeclWarning(
2964 VarDecl *VD, clang::sema::PossiblyUnreachableDiag PUD) {
2965 VarDeclPossiblyUnreachableDiags.emplace(args&: VD, args&: PUD);
2966}
2967
2968void sema::AnalysisBasedWarnings::issueWarningsForRegisteredVarDecl(
2969 VarDecl *VD) {
2970 if (!llvm::is_contained(Range&: VarDeclPossiblyUnreachableDiags, Element: VD))
2971 return;
2972
2973 AnalysisDeclContext AC(/*Mgr=*/nullptr, VD);
2974
2975 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2976 AC.getCFGBuildOptions().AddEHEdges = false;
2977 AC.getCFGBuildOptions().AddInitializers = true;
2978 AC.getCFGBuildOptions().AddImplicitDtors = true;
2979 AC.getCFGBuildOptions().AddTemporaryDtors = true;
2980 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
2981 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
2982
2983 auto Range = VarDeclPossiblyUnreachableDiags.equal_range(x: VD);
2984 auto SecondRange =
2985 llvm::make_second_range(c: llvm::make_range(x: Range.first, y: Range.second));
2986 emitPossiblyUnreachableDiags(
2987 S, AC, PUDs: std::make_pair(x: SecondRange.begin(), y: SecondRange.end()));
2988}
2989
2990// An AST Visitor that calls a callback function on each callable DEFINITION
2991// that is NOT in a dependent context:
2992class CallableVisitor : public DynamicRecursiveASTVisitor {
2993private:
2994 llvm::function_ref<void(const Decl *)> Callback;
2995 const Module *const TUModule;
2996
2997public:
2998 CallableVisitor(llvm::function_ref<void(const Decl *)> Callback,
2999 const Module *const TUModule)
3000 : Callback(Callback), TUModule(TUModule) {
3001 ShouldVisitTemplateInstantiations = true;
3002 ShouldVisitImplicitCode = false;
3003 }
3004
3005 bool TraverseDecl(Decl *Node) override {
3006 // For performance reasons, only validate the current translation unit's
3007 // module, and not modules it depends on.
3008 // See https://issues.chromium.org/issues/351909443 for details.
3009 if (Node && Node->getOwningModule() == TUModule)
3010 return DynamicRecursiveASTVisitor::TraverseDecl(D: Node);
3011 return true;
3012 }
3013
3014 bool VisitFunctionDecl(FunctionDecl *Node) override {
3015 if (cast<DeclContext>(Val: Node)->isDependentContext())
3016 return true; // Not to analyze dependent decl
3017 // `FunctionDecl->hasBody()` returns true if the function has a body
3018 // somewhere defined. But we want to know if this `Node` has a body
3019 // child. So we use `doesThisDeclarationHaveABody`:
3020 if (Node->doesThisDeclarationHaveABody())
3021 Callback(Node);
3022 return true;
3023 }
3024
3025 bool VisitBlockDecl(BlockDecl *Node) override {
3026 if (cast<DeclContext>(Val: Node)->isDependentContext())
3027 return true; // Not to analyze dependent decl
3028 Callback(Node);
3029 return true;
3030 }
3031
3032 bool VisitObjCMethodDecl(ObjCMethodDecl *Node) override {
3033 if (cast<DeclContext>(Val: Node)->isDependentContext())
3034 return true; // Not to analyze dependent decl
3035 if (Node->hasBody())
3036 Callback(Node);
3037 return true;
3038 }
3039
3040 bool VisitLambdaExpr(LambdaExpr *Node) override {
3041 return VisitFunctionDecl(Node: Node->getCallOperator());
3042 }
3043};
3044
3045// CFG build options for running the lifetime safety analysis on a function.
3046static void setLifetimeSafetyCFGBuildOptions(AnalysisDeclContext &AC) {
3047 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
3048 AC.getCFGBuildOptions().AddLifetime = true;
3049 AC.getCFGBuildOptions().AddParameterLifetimes = true;
3050 AC.getCFGBuildOptions().AddInitializers = true;
3051 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
3052 AC.getCFGBuildOptions().setAllAlwaysAdd();
3053}
3054
3055// Returns true when analysis-based warnings should be skipped for D: warnings
3056// are ignored, D is in a suppressed system header, or D is in a dependent
3057// context (which is handled later at instantiation time).
3058static bool shouldSkipAnalysisForDecl(Sema &S, const Decl *D) {
3059 DiagnosticsEngine &Diags = S.getDiagnostics();
3060 if (Diags.getIgnoreAllWarnings() ||
3061 (Diags.getSuppressSystemWarnings() &&
3062 S.SourceMgr.isInSystemHeader(Loc: D->getLocation())))
3063 return true;
3064 return cast<DeclContext>(Val: D)->isDependentContext();
3065}
3066
3067static void
3068LifetimeSafetyTUAnalysis(Sema &S, TranslationUnitDecl *TU,
3069 clang::lifetimes::LifetimeSafetyStats &LSStats) {
3070 llvm::TimeTraceScope TimeProfile("LifetimeSafetyTUAnalysis");
3071 CallGraph CG;
3072 CG.addToCallGraph(D: TU);
3073 lifetimes::LifetimeSafetySemaHelperImpl SemaHelper(S);
3074 for (auto *Node : llvm::post_order(G: &CG)) {
3075 const clang::FunctionDecl *CanonicalFD =
3076 dyn_cast_or_null<clang::FunctionDecl>(Val: Node->getDecl());
3077 if (!CanonicalFD)
3078 continue;
3079 const FunctionDecl *FD = CanonicalFD->getDefinition();
3080 if (!FD)
3081 continue;
3082 AnalysisDeclContext AC(nullptr, FD);
3083 setLifetimeSafetyCFGBuildOptions(AC);
3084 if (AC.getCFG())
3085 runLifetimeSafetyAnalysis(AC, SemaHelper: &SemaHelper,
3086 Opts: lifetimes::GetLifetimeSafetyOpts(S, D: FD),
3087 Stats&: LSStats, CollectStats: S.CollectStats);
3088 }
3089}
3090
3091static bool shouldRunUnsafeBufferUsageAnalysis(const Sema &S,
3092 SourceLocation Loc) {
3093 const DiagnosticsEngine &Diags = S.getDiagnostics();
3094 return !Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_operation, Loc) ||
3095 !Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_variable, Loc) ||
3096 !Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_usage_in_container, Loc) ||
3097 (S.getLangOpts().CPlusPlus &&
3098 (llvm::any_of(
3099 Range: UnsafeLibcCallDiagIDs,
3100 P: [&](unsigned ID) { return !Diags.isIgnored(DiagID: ID, Loc); }) ||
3101 !Diags.isIgnored(DiagID: diag::warn_unsafe_buffer_format_attr_call, Loc)));
3102}
3103
3104/// \return true iff fix-its should be emitted along with -Wunsafe-buffer-usage
3105/// warnings
3106static bool shouldEmitUnsafeBufferUsageSuggestions(const Sema &S) {
3107 return S.getLangOpts().CPlusPlus20 && S.getDiagnostics()
3108 .getDiagnosticOptions()
3109 .ShowSafeBufferUsageSuggestions;
3110}
3111
3112/// \return true iff an extra note that encourages users to turn on fix-its
3113/// should be emitted along with -Wunsafe-buffer-usage warnings
3114static bool shouldSuggestUnsafeBufferUsageSuggestions(const Sema &S) {
3115 return S.getLangOpts().CPlusPlus20 && !S.getDiagnostics()
3116 .getDiagnosticOptions()
3117 .ShowSafeBufferUsageSuggestions;
3118}
3119
3120void clang::sema::AnalysisBasedWarnings::IssueWarnings(
3121 TranslationUnitDecl *TU) {
3122 if (!TU)
3123 return; // This is unexpected, give up quietly.
3124
3125 DiagnosticsEngine &Diags = S.getDiagnostics();
3126
3127 if (S.hasUncompilableErrorOccurred() || Diags.getIgnoreAllWarnings())
3128 // exit if having uncompilable errors or ignoring all warnings:
3129 return;
3130
3131 // When the '-fsafe-buffer-usage-suggestions' option is enabled,
3132 // the '-Wunsafe-buffer-usage' analysis is performed at the end of the
3133 // translation unit. Otherwise, the analysis is more efficiently performed at
3134 // the end of each Decl during parsing.
3135 if (shouldEmitUnsafeBufferUsageSuggestions(S)) {
3136 UnsafeBufferUsageReporter R(S, /*SuggestSuggestions=*/false);
3137
3138 // The Callback function that performs analyses:
3139 auto CallAnalyzers = [&](const Decl *Node) -> void {
3140 if (Node->hasAttr<UnsafeBufferUsageAttr>())
3141 return;
3142
3143 // Perform unsafe buffer usage analysis:
3144 if (shouldRunUnsafeBufferUsageAnalysis(S, Loc: Node->getBeginLoc())) {
3145 clang::checkUnsafeBufferUsage(D: Node, Handler&: R,
3146 /*EmitSuggestion =*/EmitSuggestions: true);
3147 }
3148
3149 // More analysis ...
3150 };
3151 // Emit per-function analysis-based warnings that require the whole-TU
3152 // reasoning. Check if any of them is enabled at all before scanning the
3153 // AST:
3154 if (shouldRunUnsafeBufferUsageAnalysis(S, Loc: SourceLocation())) {
3155 CallableVisitor(CallAnalyzers, TU->getOwningModule())
3156 .TraverseTranslationUnitDecl(D: TU);
3157 }
3158 }
3159
3160 if (lifetimes::IsLifetimeSafetyEnabled(S, D: TU))
3161 LifetimeSafetyTUAnalysis(S, TU, LSStats);
3162}
3163
3164void clang::sema::AnalysisBasedWarnings::IssueWarningsForImplicitFunction(
3165 const Decl *D) {
3166 // Currently this runs only lifetime safety: a default member initializer
3167 // applied by a synthesized constructor can bind a view/pointer member to a
3168 // temporary that dies at the end of construction -- a dangling field that
3169 // would otherwise be missed.
3170 if (!D || !D->getBody())
3171 return;
3172 // In TU-end mode IsLifetimeSafetyEnabled returns false for non-TU decls, so
3173 // such definitions are reached only via the call-graph walk, not here.
3174 if (!lifetimes::IsLifetimeSafetyEnabled(S, D))
3175 return;
3176 if (shouldSkipAnalysisForDecl(S, D) || S.hasUncompilableErrorOccurred())
3177 return;
3178
3179 // A synthesized constructor can only dangle a field through an NSDMI, so skip
3180 // classes with no in-class field initializer. We do not narrow by member
3181 // type: an NSDMI can bind a borrow nested inside an aggregate member too.
3182 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: D)) {
3183 bool HasInClassInit = false;
3184 for (const FieldDecl *FD : Ctor->getParent()->fields())
3185 if (FD->hasInClassInitializer()) {
3186 HasInClassInit = true;
3187 break;
3188 }
3189 if (!HasInClassInit)
3190 return;
3191 }
3192
3193 AnalysisDeclContext AC(/*AnalysisDeclContextManager=*/nullptr, D);
3194 setLifetimeSafetyCFGBuildOptions(AC);
3195
3196 lifetimes::LifetimeSafetySemaHelperImpl SemaHelper(S);
3197 if (AC.getCFG())
3198 lifetimes::runLifetimeSafetyAnalysis(AC, SemaHelper: &SemaHelper,
3199 Opts: lifetimes::GetLifetimeSafetyOpts(S, D),
3200 Stats&: LSStats, CollectStats: S.CollectStats);
3201}
3202
3203void clang::sema::AnalysisBasedWarnings::IssueWarnings(
3204 sema::AnalysisBasedWarnings::Policy P, sema::FunctionScopeInfo *fscope,
3205 const Decl *D, QualType BlockType) {
3206
3207 // We avoid doing analysis-based warnings when there are errors for
3208 // two reasons:
3209 // (1) The CFGs often can't be constructed (if the body is invalid), so
3210 // don't bother trying.
3211 // (2) The code already has problems; running the analysis just takes more
3212 // time.
3213 DiagnosticsEngine &Diags = S.getDiagnostics();
3214
3215 if (shouldSkipAnalysisForDecl(S, D))
3216 return;
3217
3218 if (S.hasUncompilableErrorOccurred()) {
3219 // Flush out any possibly unreachable diagnostics.
3220 flushDiagnostics(S, fscope);
3221 return;
3222 }
3223
3224 const Stmt *Body = D->getBody();
3225 assert(Body);
3226
3227 // Construct the analysis context with the specified CFG build options.
3228 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
3229
3230 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
3231 // explosion for destructors that can result and the compile time hit.
3232 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
3233 AC.getCFGBuildOptions().AddEHEdges = false;
3234 AC.getCFGBuildOptions().AddInitializers = true;
3235 AC.getCFGBuildOptions().AddImplicitDtors = true;
3236 AC.getCFGBuildOptions().AddParameterLifetimes = true;
3237 AC.getCFGBuildOptions().AddTemporaryDtors = true;
3238 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
3239 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
3240
3241 bool EnableLifetimeSafetyAnalysis = lifetimes::IsLifetimeSafetyEnabled(S, D);
3242
3243 // Force that certain expressions appear as CFGElements in the CFG. This
3244 // is used to speed up various analyses.
3245 // FIXME: This isn't the right factoring. This is here for initial
3246 // prototyping, but we need a way for analyses to say what expressions they
3247 // expect to always be CFGElements and then fill in the BuildOptions
3248 // appropriately. This is essentially a layering violation.
3249 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
3250 P.enableConsumedAnalysis || EnableLifetimeSafetyAnalysis) {
3251 // Unreachable code analysis and thread safety require a linearized CFG.
3252 AC.getCFGBuildOptions().setAllAlwaysAdd();
3253 } else {
3254 AC.getCFGBuildOptions()
3255 .setAlwaysAdd(stmtClass: Stmt::BinaryOperatorClass)
3256 .setAlwaysAdd(stmtClass: Stmt::CompoundAssignOperatorClass)
3257 .setAlwaysAdd(stmtClass: Stmt::BlockExprClass)
3258 .setAlwaysAdd(stmtClass: Stmt::CStyleCastExprClass)
3259 .setAlwaysAdd(stmtClass: Stmt::DeclRefExprClass)
3260 .setAlwaysAdd(stmtClass: Stmt::ImplicitCastExprClass)
3261 .setAlwaysAdd(stmtClass: Stmt::UnaryOperatorClass);
3262 }
3263 if (EnableLifetimeSafetyAnalysis)
3264 AC.getCFGBuildOptions().AddLifetime = true;
3265
3266 // Install the logical handler.
3267 std::optional<LogicalErrorHandler> LEH;
3268 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, Loc: D->getBeginLoc())) {
3269 LEH.emplace(args&: S);
3270 AC.getCFGBuildOptions().Observer = &*LEH;
3271 }
3272
3273 // Emit delayed diagnostics.
3274 auto &PUDs = fscope->PossiblyUnreachableDiags;
3275 emitPossiblyUnreachableDiags(S, AC, PUDs: std::make_pair(x: PUDs.begin(), y: PUDs.end()));
3276
3277 // Warning: check missing 'return'
3278 if (P.enableCheckFallThrough) {
3279 const CheckFallThroughDiagnostics &CD =
3280 (isa<BlockDecl>(Val: D) ? CheckFallThroughDiagnostics::MakeForBlock()
3281 : (isa<CXXMethodDecl>(Val: D) &&
3282 cast<CXXMethodDecl>(Val: D)->getOverloadedOperator() == OO_Call &&
3283 cast<CXXMethodDecl>(Val: D)->getParent()->isLambda())
3284 ? CheckFallThroughDiagnostics::MakeForLambda()
3285 : (fscope->isCoroutine()
3286 ? CheckFallThroughDiagnostics::MakeForCoroutine(Func: D)
3287 : CheckFallThroughDiagnostics::MakeForFunction(S, Func: D)));
3288 CheckFallThroughForBody(S, D, Body, BlockType, CD, AC);
3289 }
3290
3291 // Warning: check for unreachable code
3292 if (P.enableCheckUnreachable) {
3293 // Only check for unreachable code on non-template instantiations.
3294 // Different template instantiations can effectively change the control-flow
3295 // and it is very difficult to prove that a snippet of code in a template
3296 // is unreachable for all instantiations.
3297 bool isTemplateInstantiation = false;
3298 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
3299 isTemplateInstantiation = Function->isTemplateInstantiation();
3300 if (!isTemplateInstantiation)
3301 CheckUnreachable(S, AC);
3302 }
3303
3304 // Check for thread safety violations
3305 if (P.enableThreadSafetyAnalysis) {
3306 SourceLocation FL = AC.getDecl()->getLocation();
3307 SourceLocation FEL = AC.getDecl()->getEndLoc();
3308 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
3309 if (!Diags.isIgnored(DiagID: diag::warn_thread_safety_beta, Loc: D->getBeginLoc()))
3310 Reporter.setIssueBetaWarnings(true);
3311 if (!Diags.isIgnored(DiagID: diag::warn_thread_safety_verbose, Loc: D->getBeginLoc()))
3312 Reporter.setVerbose(true);
3313
3314 threadSafety::runThreadSafetyAnalysis(AC, Handler&: Reporter,
3315 Bset: &S.ThreadSafetyDeclCache);
3316 Reporter.emitDiagnostics();
3317 }
3318
3319 // Check for violations of consumed properties.
3320 if (P.enableConsumedAnalysis) {
3321 consumed::ConsumedWarningsHandler WarningHandler(S);
3322 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
3323 Analyzer.run(AC);
3324 }
3325
3326 if (!Diags.isIgnored(DiagID: diag::warn_uninit_var, Loc: D->getBeginLoc()) ||
3327 !Diags.isIgnored(DiagID: diag::warn_sometimes_uninit_var, Loc: D->getBeginLoc()) ||
3328 !Diags.isIgnored(DiagID: diag::warn_maybe_uninit_var, Loc: D->getBeginLoc()) ||
3329 !Diags.isIgnored(DiagID: diag::warn_uninit_const_reference, Loc: D->getBeginLoc()) ||
3330 !Diags.isIgnored(DiagID: diag::warn_uninit_const_pointer, Loc: D->getBeginLoc())) {
3331 if (CFG *cfg = AC.getCFG()) {
3332 UninitValsDiagReporter reporter(S);
3333 UninitVariablesAnalysisStats stats;
3334 std::memset(s: &stats, c: 0, n: sizeof(UninitVariablesAnalysisStats));
3335 runUninitializedVariablesAnalysis(dc: *cast<DeclContext>(Val: D), cfg: *cfg, ac&: AC,
3336 handler&: reporter, stats);
3337
3338 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
3339 ++NumUninitAnalysisFunctions;
3340 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
3341 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
3342 MaxUninitAnalysisVariablesPerFunction =
3343 std::max(a: MaxUninitAnalysisVariablesPerFunction,
3344 b: stats.NumVariablesAnalyzed);
3345 MaxUninitAnalysisBlockVisitsPerFunction =
3346 std::max(a: MaxUninitAnalysisBlockVisitsPerFunction,
3347 b: stats.NumBlockVisits);
3348 }
3349 }
3350 }
3351
3352 if (EnableLifetimeSafetyAnalysis) {
3353 if (AC.getCFG()) {
3354 lifetimes::LifetimeSafetySemaHelperImpl LifetimeSafetySemaHelper(S);
3355 lifetimes::runLifetimeSafetyAnalysis(
3356 AC, SemaHelper: &LifetimeSafetySemaHelper, Opts: lifetimes::GetLifetimeSafetyOpts(S, D),
3357 Stats&: LSStats, CollectStats: S.CollectStats);
3358 }
3359 }
3360 // Check for violations of "called once" parameter properties.
3361 if (S.getLangOpts().ObjC && !S.getLangOpts().CPlusPlus &&
3362 shouldAnalyzeCalledOnceParameters(Diags, At: D->getBeginLoc())) {
3363 if (AC.getCFG()) {
3364 CalledOnceCheckReporter Reporter(S, IPData->CalledOnceData);
3365 checkCalledOnceParameters(
3366 AC, Handler&: Reporter,
3367 CheckConventionalParameters: shouldAnalyzeCalledOnceConventions(Diags, At: D->getBeginLoc()));
3368 }
3369 }
3370
3371 bool FallThroughDiagFull =
3372 !Diags.isIgnored(DiagID: diag::warn_unannotated_fallthrough, Loc: D->getBeginLoc());
3373 bool FallThroughDiagPerFunction = !Diags.isIgnored(
3374 DiagID: diag::warn_unannotated_fallthrough_per_function, Loc: D->getBeginLoc());
3375 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
3376 fscope->HasFallthroughStmt) {
3377 DiagnoseSwitchLabelsFallthrough(S, AC, PerFunction: !FallThroughDiagFull);
3378 }
3379
3380 if (S.getLangOpts().ObjCWeak &&
3381 !Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: D->getBeginLoc()))
3382 diagnoseRepeatedUseOfWeak(S, CurFn: fscope, D, PM: AC.getParentMap());
3383
3384
3385 // Check for infinite self-recursion in functions
3386 if (!Diags.isIgnored(DiagID: diag::warn_infinite_recursive_function,
3387 Loc: D->getBeginLoc())) {
3388 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
3389 checkRecursiveFunction(S, FD, Body, AC);
3390 }
3391 }
3392
3393 // Check for throw out of non-throwing function.
3394 if (!Diags.isIgnored(DiagID: diag::warn_throw_in_noexcept_func, Loc: D->getBeginLoc()))
3395 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
3396 if (S.getLangOpts().CPlusPlus && !fscope->isCoroutine() && isNoexcept(FD))
3397 checkThrowInNonThrowingFunc(S, FD, AC);
3398
3399 // If none of the previous checks caused a CFG build, trigger one here
3400 // for the logical error handler.
3401 if (LogicalErrorHandler::hasActiveDiagnostics(Diags, Loc: D->getBeginLoc())) {
3402 AC.getCFG();
3403 }
3404
3405 // Clear any of our policy overrides.
3406 clearOverrides();
3407
3408 // Collect statistics about the CFG if it was built.
3409 if (S.CollectStats && AC.isCFGBuilt()) {
3410 ++NumFunctionsAnalyzed;
3411 if (CFG *cfg = AC.getCFG()) {
3412 // If we successfully built a CFG for this context, record some more
3413 // detail information about it.
3414 NumCFGBlocks += cfg->getNumBlockIDs();
3415 MaxCFGBlocksPerFunction = std::max(a: MaxCFGBlocksPerFunction,
3416 b: cfg->getNumBlockIDs());
3417 } else {
3418 ++NumFunctionsWithBadCFGs;
3419 }
3420 }
3421
3422 // If the '-fsafe-buffer-usage-suggestions' option is not specified or C++20
3423 // is not available, '-Wunsafe-buffer-usage' warnings are analyzed at the end
3424 // of each Decl. This is because only '-fsafe-buffer-usage-suggestions'
3425 // requires visibility of the whole translation unit, hence the cumbersome
3426 // post-TU analysis, which deserializes and scans pre-compiled ASTs.
3427 if (!shouldEmitUnsafeBufferUsageSuggestions(S) &&
3428 !D->hasAttr<UnsafeBufferUsageAttr>()) {
3429 UnsafeBufferUsageReporter R(S,
3430 shouldSuggestUnsafeBufferUsageSuggestions(S));
3431
3432 // Perform unsafe buffer usage analysis:
3433 if (shouldRunUnsafeBufferUsageAnalysis(S, Loc: D->getBeginLoc())) {
3434 clang::checkUnsafeBufferUsage(
3435 D, Handler&: R, /*UnsafeBufferUsageShouldEmitSuggestions=*/EmitSuggestions: false);
3436 }
3437 }
3438}
3439
3440void clang::sema::AnalysisBasedWarnings::PrintStats() const {
3441 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
3442
3443 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
3444 unsigned AvgCFGBlocksPerFunction =
3445 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
3446 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
3447 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
3448 << " " << NumCFGBlocks << " CFG blocks built.\n"
3449 << " " << AvgCFGBlocksPerFunction
3450 << " average CFG blocks per function.\n"
3451 << " " << MaxCFGBlocksPerFunction
3452 << " max CFG blocks per function.\n";
3453
3454 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
3455 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
3456 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
3457 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
3458 llvm::errs() << NumUninitAnalysisFunctions
3459 << " functions analyzed for uninitialiazed variables\n"
3460 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
3461 << " " << AvgUninitVariablesPerFunction
3462 << " average variables per function.\n"
3463 << " " << MaxUninitAnalysisVariablesPerFunction
3464 << " max variables per function.\n"
3465 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
3466 << " " << AvgUninitBlockVisitsPerFunction
3467 << " average block visits per function.\n"
3468 << " " << MaxUninitAnalysisBlockVisitsPerFunction
3469 << " max block visits per function.\n";
3470 clang::lifetimes::printStats(Stats: LSStats);
3471}
3472