Bug Summary

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