Bug Summary

File:tools/clang/lib/Sema/AnalysisBasedWarnings.cpp
Warning:line 1414, column 12
Potential memory leak

Annotated Source Code

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