blob: 20d83fe507a9bca853b582ff086c0ddac0393e80 [file] [log] [blame]
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001//=- 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
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000018#include "clang/Sema/ScopeInfo.h"
Ted Kremenekd068aab2010-03-20 21:11:09 +000019#include "clang/Basic/SourceManager.h"
Ted Kremenekfbb178a2011-01-21 19:41:46 +000020#include "clang/Lex/Preprocessor.h"
John McCall7cd088e2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
John McCall384aff82010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000023#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
Ted Kremenek6f417152011-04-04 20:56:00 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000028#include "clang/AST/StmtVisitor.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000029#include "clang/Analysis/AnalysisContext.h"
30#include "clang/Analysis/CFG.h"
31#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremenek351ba912011-02-23 01:52:04 +000032#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
33#include "clang/Analysis/CFGStmtMap.h"
Ted Kremenek6f342132011-03-15 03:17:07 +000034#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000035#include "llvm/ADT/BitVector.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000036#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/ImmutableMap.h"
38#include "llvm/ADT/PostOrderIterator.h"
39#include "llvm/ADT/SmallVector.h"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000040#include "llvm/Support/Casting.h"
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +000041#include <algorithm>
42#include <vector>
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000043
44using namespace clang;
45
46//===----------------------------------------------------------------------===//
47// Unreachable code analysis.
48//===----------------------------------------------------------------------===//
49
50namespace {
51 class UnreachableCodeHandler : public reachable_code::Callback {
52 Sema &S;
53 public:
54 UnreachableCodeHandler(Sema &s) : S(s) {}
55
56 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
57 S.Diag(L, diag::warn_unreachable) << R1 << R2;
58 }
59 };
60}
61
62/// CheckUnreachable - Check for unreachable code.
63static void CheckUnreachable(Sema &S, AnalysisContext &AC) {
64 UnreachableCodeHandler UC(S);
65 reachable_code::FindUnreachableCode(AC, UC);
66}
67
68//===----------------------------------------------------------------------===//
69// Check for missing return value.
70//===----------------------------------------------------------------------===//
71
John McCall16565aa2010-05-16 09:34:11 +000072enum ControlFlowKind {
73 UnknownFallThrough,
74 NeverFallThrough,
75 MaybeFallThrough,
76 AlwaysFallThrough,
77 NeverFallThroughOrReturn
78};
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000079
80/// CheckFallThrough - Check that we don't fall off the end of a
81/// Statement that should return a value.
82///
83/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
84/// MaybeFallThrough iff we might or might not fall off the end,
85/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
86/// return. We assume NeverFallThrough iff we never fall off the end of the
87/// statement but we may return. We assume that functions not marked noreturn
88/// will return.
89static ControlFlowKind CheckFallThrough(AnalysisContext &AC) {
90 CFG *cfg = AC.getCFG();
John McCall16565aa2010-05-16 09:34:11 +000091 if (cfg == 0) return UnknownFallThrough;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000092
93 // The CFG leaves in dead things, and we don't want the dead code paths to
94 // confuse us, so we mark all live things first.
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000095 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +000096 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000097 live);
98
99 bool AddEHEdges = AC.getAddEHEdges();
100 if (!AddEHEdges && count != cfg->getNumBlockIDs())
101 // When there are things remaining dead, and we didn't add EH edges
102 // from CallExprs to the catch clauses, we have to go back and
103 // mark them as live.
104 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
105 CFGBlock &b = **I;
106 if (!live[b.getBlockID()]) {
107 if (b.pred_begin() == b.pred_end()) {
108 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
109 // When not adding EH edges from calls, catch clauses
110 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +0000111 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000112 continue;
113 }
114 }
115 }
116
117 // Now we know what is live, we check the live precessors of the exit block
118 // and look for fall through paths, being careful to ignore normal returns,
119 // and exceptional paths.
120 bool HasLiveReturn = false;
121 bool HasFakeEdge = false;
122 bool HasPlainEdge = false;
123 bool HasAbnormalEdge = false;
Ted Kremenek90b828a2010-09-09 00:06:07 +0000124
125 // Ignore default cases that aren't likely to be reachable because all
126 // enums in a switch(X) have explicit case statements.
127 CFGBlock::FilterOptions FO;
128 FO.IgnoreDefaultsWithCoveredEnums = 1;
129
130 for (CFGBlock::filtered_pred_iterator
131 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
132 const CFGBlock& B = **I;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000133 if (!live[B.getBlockID()])
134 continue;
Ted Kremenek5811f592011-01-26 04:49:52 +0000135
136 // Destructors can appear after the 'return' in the CFG. This is
137 // normal. We need to look pass the destructors for the return
138 // statement (if it exists).
139 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000140 bool hasNoReturnDtor = false;
141
Ted Kremenek5811f592011-01-26 04:49:52 +0000142 for ( ; ri != re ; ++ri) {
143 CFGElement CE = *ri;
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000144
145 // FIXME: The right solution is to just sever the edges in the
146 // CFG itself.
147 if (const CFGImplicitDtor *iDtor = ri->getAs<CFGImplicitDtor>())
Ted Kremenekc5aff442011-03-03 01:21:32 +0000148 if (iDtor->isNoReturn(AC.getASTContext())) {
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000149 hasNoReturnDtor = true;
150 HasFakeEdge = true;
151 break;
152 }
153
Ted Kremenek5811f592011-01-26 04:49:52 +0000154 if (isa<CFGStmt>(CE))
155 break;
156 }
157
Ted Kremenekc9f8f5a2011-03-02 20:32:29 +0000158 if (hasNoReturnDtor)
159 continue;
160
Ted Kremenek5811f592011-01-26 04:49:52 +0000161 // No more CFGElements in the block?
162 if (ri == re) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000163 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
164 HasAbnormalEdge = true;
165 continue;
166 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000167 // A labeled empty statement, or the entry block...
168 HasPlainEdge = true;
169 continue;
170 }
Ted Kremenekf39e6a32011-01-25 22:50:47 +0000171
Ted Kremenek5811f592011-01-26 04:49:52 +0000172 CFGStmt CS = cast<CFGStmt>(*ri);
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000173 const Stmt *S = CS.getStmt();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000174 if (isa<ReturnStmt>(S)) {
175 HasLiveReturn = true;
176 continue;
177 }
178 if (isa<ObjCAtThrowStmt>(S)) {
179 HasFakeEdge = true;
180 continue;
181 }
182 if (isa<CXXThrowExpr>(S)) {
183 HasFakeEdge = true;
184 continue;
185 }
186 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
187 if (AS->isMSAsm()) {
188 HasFakeEdge = true;
189 HasLiveReturn = true;
190 continue;
191 }
192 }
193 if (isa<CXXTryStmt>(S)) {
194 HasAbnormalEdge = true;
195 continue;
196 }
197
198 bool NoReturnEdge = false;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000199 if (const CallExpr *C = dyn_cast<CallExpr>(S)) {
John McCall259d48e2010-04-30 07:10:06 +0000200 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
201 == B.succ_end()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000202 HasAbnormalEdge = true;
203 continue;
204 }
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000205 const Expr *CEE = C->getCallee()->IgnoreParenCasts();
John McCall1de85332011-05-11 07:19:11 +0000206 QualType calleeType = CEE->getType();
207 if (calleeType == AC.getASTContext().BoundMemberTy) {
208 calleeType = Expr::findBoundMemberType(CEE);
209 assert(!calleeType.isNull() && "analyzing unresolved call?");
210 }
211 if (getFunctionExtInfo(calleeType).getNoReturn()) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000212 NoReturnEdge = true;
213 HasFakeEdge = true;
Ted Kremenekf1d10d92011-08-23 23:05:04 +0000214 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
215 const ValueDecl *VD = DRE->getDecl();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000216 if (VD->hasAttr<NoReturnAttr>()) {
217 NoReturnEdge = true;
218 HasFakeEdge = true;
219 }
220 }
221 }
222 // FIXME: Add noreturn message sends.
223 if (NoReturnEdge == false)
224 HasPlainEdge = true;
225 }
226 if (!HasPlainEdge) {
227 if (HasLiveReturn)
228 return NeverFallThrough;
229 return NeverFallThroughOrReturn;
230 }
231 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
232 return MaybeFallThrough;
233 // This says AlwaysFallThrough for calls to functions that are not marked
234 // noreturn, that don't return. If people would like this warning to be more
235 // accurate, such functions should be marked as noreturn.
236 return AlwaysFallThrough;
237}
238
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000239namespace {
240
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000241struct CheckFallThroughDiagnostics {
242 unsigned diag_MaybeFallThrough_HasNoReturn;
243 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
244 unsigned diag_AlwaysFallThrough_HasNoReturn;
245 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
246 unsigned diag_NeverFallThroughOrReturn;
247 bool funMode;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000248 SourceLocation FuncLoc;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000249
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000250 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000251 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000252 D.FuncLoc = Func->getLocation();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000253 D.diag_MaybeFallThrough_HasNoReturn =
254 diag::warn_falloff_noreturn_function;
255 D.diag_MaybeFallThrough_ReturnsNonVoid =
256 diag::warn_maybe_falloff_nonvoid_function;
257 D.diag_AlwaysFallThrough_HasNoReturn =
258 diag::warn_falloff_noreturn_function;
259 D.diag_AlwaysFallThrough_ReturnsNonVoid =
260 diag::warn_falloff_nonvoid_function;
Douglas Gregorca7eaee2010-04-16 23:28:44 +0000261
262 // Don't suggest that virtual functions be marked "noreturn", since they
263 // might be overridden by non-noreturn functions.
264 bool isVirtualMethod = false;
265 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
266 isVirtualMethod = Method->isVirtual();
267
268 if (!isVirtualMethod)
269 D.diag_NeverFallThroughOrReturn =
270 diag::warn_suggest_noreturn_function;
271 else
272 D.diag_NeverFallThroughOrReturn = 0;
273
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000274 D.funMode = true;
275 return D;
276 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000277
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000278 static CheckFallThroughDiagnostics MakeForBlock() {
279 CheckFallThroughDiagnostics D;
280 D.diag_MaybeFallThrough_HasNoReturn =
281 diag::err_noreturn_block_has_return_expr;
282 D.diag_MaybeFallThrough_ReturnsNonVoid =
283 diag::err_maybe_falloff_nonvoid_block;
284 D.diag_AlwaysFallThrough_HasNoReturn =
285 diag::err_noreturn_block_has_return_expr;
286 D.diag_AlwaysFallThrough_ReturnsNonVoid =
287 diag::err_falloff_nonvoid_block;
288 D.diag_NeverFallThroughOrReturn =
289 diag::warn_suggest_noreturn_block;
290 D.funMode = false;
291 return D;
292 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000293
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000294 bool checkDiagnostics(Diagnostic &D, bool ReturnsVoid,
295 bool HasNoReturn) const {
296 if (funMode) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000297 return (ReturnsVoid ||
298 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
299 FuncLoc) == Diagnostic::Ignored)
300 && (!HasNoReturn ||
301 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
302 FuncLoc) == Diagnostic::Ignored)
303 && (!ReturnsVoid ||
304 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
305 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000306 }
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000307
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000308 // For blocks.
309 return ReturnsVoid && !HasNoReturn
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +0000310 && (!ReturnsVoid ||
311 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
312 == Diagnostic::Ignored);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000313 }
314};
315
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000316}
317
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000318/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
319/// function that should return a value. Check that we don't fall off the end
320/// of a noreturn function. We assume that functions and blocks not marked
321/// noreturn will return.
322static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000323 const BlockExpr *blkExpr,
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000324 const CheckFallThroughDiagnostics& CD,
325 AnalysisContext &AC) {
326
327 bool ReturnsVoid = false;
328 bool HasNoReturn = false;
329
330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
331 ReturnsVoid = FD->getResultType()->isVoidType();
332 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
Rafael Espindola264ba482010-03-30 20:24:48 +0000333 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000334 }
335 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
336 ReturnsVoid = MD->getResultType()->isVoidType();
337 HasNoReturn = MD->hasAttr<NoReturnAttr>();
338 }
339 else if (isa<BlockDecl>(D)) {
Ted Kremenek3ed6fc02011-02-23 01:51:48 +0000340 QualType BlockTy = blkExpr->getType();
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000341 if (const FunctionType *FT =
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000342 BlockTy->getPointeeType()->getAs<FunctionType>()) {
343 if (FT->getResultType()->isVoidType())
344 ReturnsVoid = true;
345 if (FT->getNoReturnAttr())
346 HasNoReturn = true;
347 }
348 }
349
350 Diagnostic &Diags = S.getDiagnostics();
351
352 // Short circuit for compilation speed.
353 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
354 return;
Ted Kremenekd064fdc2010-03-23 00:13:23 +0000355
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000356 // FIXME: Function try block
357 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
358 switch (CheckFallThrough(AC)) {
John McCall16565aa2010-05-16 09:34:11 +0000359 case UnknownFallThrough:
360 break;
361
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000362 case MaybeFallThrough:
363 if (HasNoReturn)
364 S.Diag(Compound->getRBracLoc(),
365 CD.diag_MaybeFallThrough_HasNoReturn);
366 else if (!ReturnsVoid)
367 S.Diag(Compound->getRBracLoc(),
368 CD.diag_MaybeFallThrough_ReturnsNonVoid);
369 break;
370 case AlwaysFallThrough:
371 if (HasNoReturn)
372 S.Diag(Compound->getRBracLoc(),
373 CD.diag_AlwaysFallThrough_HasNoReturn);
374 else if (!ReturnsVoid)
375 S.Diag(Compound->getRBracLoc(),
376 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
377 break;
378 case NeverFallThroughOrReturn:
Chandler Carruthb0656ec2011-08-31 09:01:53 +0000379 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
380 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
381 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
382 << FD;
383 } else {
384 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
385 }
386 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +0000387 break;
388 case NeverFallThrough:
389 break;
390 }
391 }
392}
393
394//===----------------------------------------------------------------------===//
Ted Kremenek610068c2011-01-15 02:58:47 +0000395// -Wuninitialized
396//===----------------------------------------------------------------------===//
397
Ted Kremenek6f417152011-04-04 20:56:00 +0000398namespace {
Chandler Carruth9f649462011-04-05 06:48:00 +0000399/// ContainsReference - A visitor class to search for references to
400/// a particular declaration (the needle) within any evaluated component of an
401/// expression (recursively).
Ted Kremenek6f417152011-04-04 20:56:00 +0000402class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth9f649462011-04-05 06:48:00 +0000403 bool FoundReference;
404 const DeclRefExpr *Needle;
405
Ted Kremenek6f417152011-04-04 20:56:00 +0000406public:
Chandler Carruth9f649462011-04-05 06:48:00 +0000407 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
408 : EvaluatedExprVisitor<ContainsReference>(Context),
409 FoundReference(false), Needle(Needle) {}
410
411 void VisitExpr(Expr *E) {
Ted Kremenek6f417152011-04-04 20:56:00 +0000412 // Stop evaluating if we already have a reference.
Chandler Carruth9f649462011-04-05 06:48:00 +0000413 if (FoundReference)
Ted Kremenek6f417152011-04-04 20:56:00 +0000414 return;
Chandler Carruth9f649462011-04-05 06:48:00 +0000415
416 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000417 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000418
419 void VisitDeclRefExpr(DeclRefExpr *E) {
420 if (E == Needle)
421 FoundReference = true;
422 else
423 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenek6f417152011-04-04 20:56:00 +0000424 }
Chandler Carruth9f649462011-04-05 06:48:00 +0000425
426 bool doesContainReference() const { return FoundReference; }
Ted Kremenek6f417152011-04-04 20:56:00 +0000427};
428}
429
Chandler Carruth262d50e2011-04-05 18:27:05 +0000430/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
431/// uninitialized variable. This manages the different forms of diagnostic
432/// emitted for particular types of uses. Returns true if the use was diagnosed
433/// as a warning. If a pariticular use is one we omit warnings for, returns
434/// false.
435static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Chandler Carruth64fb9592011-04-05 18:18:08 +0000436 const Expr *E, bool isAlwaysUninit) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000437 bool isSelfInit = false;
438
439 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
440 if (isAlwaysUninit) {
441 // Inspect the initializer of the variable declaration which is
442 // being referenced prior to its initialization. We emit
443 // specialized diagnostics for self-initialization, and we
444 // specifically avoid warning about self references which take the
445 // form of:
446 //
447 // int x = x;
448 //
449 // This is used to indicate to GCC that 'x' is intentionally left
450 // uninitialized. Proven code paths which access 'x' in
451 // an uninitialized state after this will still warn.
452 //
453 // TODO: Should we suppress maybe-uninitialized warnings for
454 // variables initialized in this way?
455 if (const Expr *Initializer = VD->getInit()) {
456 if (DRE == Initializer->IgnoreParenImpCasts())
Chandler Carruth262d50e2011-04-05 18:27:05 +0000457 return false;
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000458
459 ContainsReference CR(S.Context, DRE);
460 CR.Visit(const_cast<Expr*>(Initializer));
461 isSelfInit = CR.doesContainReference();
462 }
463 if (isSelfInit) {
464 S.Diag(DRE->getLocStart(),
465 diag::warn_uninit_self_reference_in_init)
466 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
467 } else {
468 S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
469 << VD->getDeclName() << DRE->getSourceRange();
470 }
471 } else {
472 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
473 << VD->getDeclName() << DRE->getSourceRange();
474 }
475 } else {
476 const BlockExpr *BE = cast<BlockExpr>(E);
477 S.Diag(BE->getLocStart(),
478 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
479 : diag::warn_maybe_uninit_var_captured_by_block)
480 << VD->getDeclName();
481 }
482
483 // Report where the variable was declared when the use wasn't within
484 // the initializer of that declaration.
485 if (!isSelfInit)
486 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
487 << VD->getDeclName();
488
Chandler Carruth262d50e2011-04-05 18:27:05 +0000489 return true;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000490}
491
Chandler Carruth262d50e2011-04-05 18:27:05 +0000492static void SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000493 // Don't issue a fixit if there is already an initializer.
494 if (VD->getInit())
495 return;
496
497 // Suggest possible initialization (if any).
498 const char *initialization = 0;
499 QualType VariableTy = VD->getType().getCanonicalType();
500
Douglas Gregor8ba44262011-07-02 00:59:18 +0000501 if (VariableTy->isObjCObjectPointerType() ||
502 VariableTy->isBlockPointerType()) {
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000503 // Check if 'nil' is defined.
504 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil")))
505 initialization = " = nil";
506 else
507 initialization = " = 0";
508 }
509 else if (VariableTy->isRealFloatingType())
510 initialization = " = 0.0";
511 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus)
512 initialization = " = false";
513 else if (VariableTy->isEnumeralType())
514 return;
Douglas Gregor8ba44262011-07-02 00:59:18 +0000515 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) {
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000516 if (S.Context.getLangOptions().CPlusPlus0x)
517 initialization = " = nullptr";
Douglas Gregor8ba44262011-07-02 00:59:18 +0000518 // Check if 'NULL' is defined.
Douglas Gregorcc68c9b2011-08-27 00:18:50 +0000519 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL")))
Douglas Gregor8ba44262011-07-02 00:59:18 +0000520 initialization = " = NULL";
521 else
522 initialization = " = 0";
523 }
Chandler Carruth4c4983b2011-04-05 18:18:05 +0000524 else if (VariableTy->isScalarType())
525 initialization = " = 0";
526
527 if (initialization) {
528 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
529 S.Diag(loc, diag::note_var_fixit_add_initialization)
530 << FixItHint::CreateInsertion(loc, initialization);
531 }
532}
533
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000534typedef std::pair<const Expr*, bool> UninitUse;
535
Ted Kremenek610068c2011-01-15 02:58:47 +0000536namespace {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000537struct SLocSort {
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000538 bool operator()(const UninitUse &a, const UninitUse &b) {
539 SourceLocation aLoc = a.first->getLocStart();
540 SourceLocation bLoc = b.first->getLocStart();
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000541 return aLoc.getRawEncoding() < bLoc.getRawEncoding();
542 }
543};
544
Ted Kremenek610068c2011-01-15 02:58:47 +0000545class UninitValsDiagReporter : public UninitVariablesHandler {
546 Sema &S;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000547 typedef SmallVector<UninitUse, 2> UsesVec;
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000548 typedef llvm::DenseMap<const VarDecl *, UsesVec*> UsesMap;
549 UsesMap *uses;
550
Ted Kremenek610068c2011-01-15 02:58:47 +0000551public:
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000552 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
553 ~UninitValsDiagReporter() {
554 flushDiagnostics();
555 }
Ted Kremenek610068c2011-01-15 02:58:47 +0000556
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000557 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
558 bool isAlwaysUninit) {
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000559 if (!uses)
560 uses = new UsesMap();
561
562 UsesVec *&vec = (*uses)[vd];
563 if (!vec)
564 vec = new UsesVec();
565
Ted Kremenekf7bafc72011-03-15 04:57:38 +0000566 vec->push_back(std::make_pair(ex, isAlwaysUninit));
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000567 }
568
569 void flushDiagnostics() {
570 if (!uses)
571 return;
Ted Kremenek609e3172011-02-02 23:35:53 +0000572
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000573 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
574 const VarDecl *vd = i->first;
575 UsesVec *vec = i->second;
Ted Kremenek609e3172011-02-02 23:35:53 +0000576
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000577 // Sort the uses by their SourceLocations. While not strictly
578 // guaranteed to produce them in line/column order, this will provide
579 // a stable ordering.
580 std::sort(vec->begin(), vec->end(), SLocSort());
581
Chandler Carruth64fb9592011-04-05 18:18:08 +0000582 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
583 ++vi) {
Chandler Carruth262d50e2011-04-05 18:27:05 +0000584 if (!DiagnoseUninitializedUse(S, vd, vi->first,
585 /*isAlwaysUninit=*/vi->second))
586 continue;
587
Chandler Carruthd837c0d2011-07-22 05:27:52 +0000588 SuggestInitializationFixit(S, vd);
589
590 // Skip further diagnostics for this variable. We try to warn only on
591 // the first point at which a variable is used uninitialized.
592 break;
Chandler Carruth64fb9592011-04-05 18:18:08 +0000593 }
Ted Kremenekd40066b2011-04-04 23:29:12 +0000594
Ted Kremenek94b1b4d2011-01-21 19:41:41 +0000595 delete vec;
596 }
597 delete uses;
Ted Kremenek610068c2011-01-15 02:58:47 +0000598 }
599};
600}
601
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000602
603//===----------------------------------------------------------------------===//
604// -Wthread-safety
605//===----------------------------------------------------------------------===//
606
607namespace {
608/// \brief Implements a set of CFGBlocks using a BitVector.
609///
610/// This class contains a minimal interface, primarily dictated by the SetType
611/// template parameter of the llvm::po_iterator template, as used with external
612/// storage. We also use this set to keep track of which CFGBlocks we visit
613/// during the analysis.
614class CFGBlockSet {
615 llvm::BitVector VisitedBlockIDs;
616
617public:
618 // po_iterator requires this iterator, but the only interface needed is the
619 // value_type typedef.
620 struct iterator {
621 typedef const CFGBlock *value_type;
622 };
623
624 CFGBlockSet() {}
625 CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) {}
626
627 /// \brief Set the bit associated with a particular CFGBlock.
628 /// This is the important method for the SetType template parameter.
629 bool insert(const CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000630 // Note that insert() is called by po_iterator, which doesn't check to make
631 // sure that Block is non-null. Moreover, the CFGBlock iterator will
632 // occasionally hand out null pointers for pruned edges, so we catch those
633 // here.
634 if (Block == 0)
635 return false; // if an edge is trivially false.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000636 if (VisitedBlockIDs.test(Block->getBlockID()))
637 return false;
638 VisitedBlockIDs.set(Block->getBlockID());
639 return true;
640 }
641
642 /// \brief Check if the bit for a CFGBlock has been already set.
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +0000643 /// This method is for tracking visited blocks in the main threadsafety loop.
644 /// Block must not be null.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000645 bool alreadySet(const CFGBlock *Block) {
646 return VisitedBlockIDs.test(Block->getBlockID());
647 }
648};
649
650/// \brief We create a helper class which we use to iterate through CFGBlocks in
651/// the topological order.
652class TopologicallySortedCFG {
653 typedef llvm::po_iterator<const CFG*, CFGBlockSet, true> po_iterator;
654
655 std::vector<const CFGBlock*> Blocks;
656
657public:
658 typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
659
660 TopologicallySortedCFG(const CFG *CFGraph) {
661 Blocks.reserve(CFGraph->getNumBlockIDs());
662 CFGBlockSet BSet(CFGraph);
663
664 for (po_iterator I = po_iterator::begin(CFGraph, BSet),
665 E = po_iterator::end(CFGraph, BSet); I != E; ++I) {
666 Blocks.push_back(*I);
667 }
668 }
669
670 iterator begin() {
671 return Blocks.rbegin();
672 }
673
674 iterator end() {
675 return Blocks.rend();
676 }
677};
678
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000679/// \brief A MutexID object uniquely identifies a particular mutex, and
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000680/// is built from an Expr* (i.e. calling a lock function).
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000681///
682/// Thread-safety analysis works by comparing lock expressions. Within the
683/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000684/// a particular mutex object at run-time. Subsequent occurrences of the same
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000685/// expression (where "same" means syntactic equality) will refer to the same
686/// run-time object if three conditions hold:
687/// (1) Local variables in the expression, such as "x" have not changed.
688/// (2) Values on the heap that affect the expression have not changed.
689/// (3) The expression involves only pure function calls.
690/// The current implementation assumes, but does not verify, that multiple uses
691/// of the same lock expression satisfies these criteria.
692///
693/// Clang introduces an additional wrinkle, which is that it is difficult to
694/// derive canonical expressions, or compare expressions directly for equality.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000695/// Thus, we identify a mutex not by an Expr, but by the set of named
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000696/// declarations that are referenced by the Expr. In other words,
697/// x->foo->bar.mu will be a four element vector with the Decls for
698/// mu, bar, and foo, and x. The vector will uniquely identify the expression
699/// for all practical purposes.
700///
701/// Note we will need to perform substitution on "this" and function parameter
702/// names when constructing a lock expression.
703///
704/// For example:
705/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
706/// void myFunc(C *X) { ... X->lock() ... }
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000707/// The original expression for the mutex acquired by myFunc is "this->Mu", but
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000708/// "X" is substituted for "this" so we get X->Mu();
709///
710/// For another example:
711/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
712/// MyList *MyL;
713/// foo(MyL); // requires lock MyL->Mu to be held
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000714class MutexID {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000715 SmallVector<NamedDecl*, 2> DeclSeq;
716
717 /// Build a Decl sequence representing the lock from the given expression.
718 /// Recursive function that bottoms out when the final DeclRefExpr is reached.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000719 void buildMutexID(Expr *Exp) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000720 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
721 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
722 DeclSeq.push_back(ND);
723 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
724 NamedDecl *ND = ME->getMemberDecl();
725 DeclSeq.push_back(ND);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000726 buildMutexID(ME->getBase());
Caitlin Sadowskieff98fc2011-09-08 17:42:22 +0000727 } else if (isa<CXXThisExpr>(Exp)) {
728 return;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000729 } else {
730 // FIXME: add diagnostic
731 llvm::report_fatal_error("Expected lock expression!");
732 }
733 }
734
735public:
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000736 MutexID(Expr *LExpr) {
737 buildMutexID(LExpr);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000738 assert(!DeclSeq.empty());
739 }
740
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000741 bool operator==(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000742 return DeclSeq == other.DeclSeq;
743 }
744
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000745 bool operator!=(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000746 return !(*this == other);
747 }
748
749 // SmallVector overloads Operator< to do lexicographic ordering. Note that
750 // we use pointer equality (and <) to compare NamedDecls. This means the order
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000751 // of MutexIDs in a lockset is nondeterministic. In order to output
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000752 // diagnostics in a deterministic ordering, we must order all diagnostics to
753 // output by SourceLocation when iterating through this lockset.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000754 bool operator<(const MutexID &other) const {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000755 return DeclSeq < other.DeclSeq;
756 }
757
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000758 /// \brief Returns the name of the first Decl in the list for a given MutexID;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000759 /// e.g. the lock expression foo.bar() has name "bar".
760 /// The caret will point unambiguously to the lock expression, so using this
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000761 /// name in diagnostics is a way to get simple, and consistent, mutex names.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000762 /// We do not want to output the entire expression text for security reasons.
763 StringRef getName() const {
764 return DeclSeq.front()->getName();
765 }
766
767 void Profile(llvm::FoldingSetNodeID &ID) const {
768 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
769 E = DeclSeq.end(); I != E; ++I) {
770 ID.AddPointer(*I);
771 }
772 }
773};
774
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000775enum LockKind {
776 LK_Shared,
777 LK_Exclusive
778};
779
780enum AccessKind {
781 AK_Read,
782 AK_Written
783};
784
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000785/// \brief This is a helper class that stores info about the most recent
786/// accquire of a Lock.
787///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000788/// The main body of the analysis maps MutexIDs to LockDatas.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000789struct LockData {
790 SourceLocation AcquireLoc;
791
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000792 /// \brief LKind stores whether a lock is held shared or exclusively.
793 /// Note that this analysis does not currently support either re-entrant
794 /// locking or lock "upgrading" and "downgrading" between exclusive and
795 /// shared.
796 ///
797 /// FIXME: add support for re-entrant locking and lock up/downgrading
798 LockKind LKind;
799
800 LockData(SourceLocation AcquireLoc, LockKind LKind)
801 : AcquireLoc(AcquireLoc), LKind(LKind) {}
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000802
803 bool operator==(const LockData &other) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000804 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000805 }
806
807 bool operator!=(const LockData &other) const {
808 return !(*this == other);
809 }
810
811 void Profile(llvm::FoldingSetNodeID &ID) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000812 ID.AddInteger(AcquireLoc.getRawEncoding());
813 ID.AddInteger(LKind);
814 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000815};
816
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000817/// A Lockset maps each MutexID (defined above) to information about how it has
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000818/// been locked.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000819typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000820
821/// \brief We use this class to visit different types of expressions in
822/// CFGBlocks, and build up the lockset.
823/// An expression may cause us to add or remove locks from the lockset, or else
824/// output error messages related to missing locks.
825/// FIXME: In future, we may be able to not inherit from a visitor.
826class BuildLockset : public StmtVisitor<BuildLockset> {
827 Sema &S;
828 Lockset LSet;
829 Lockset::Factory &LocksetFactory;
830
831 // Helper functions
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000832 void removeLock(SourceLocation UnlockLoc, Expr *LockExp);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000833 void addLock(SourceLocation LockLoc, Expr *LockExp, LockKind LK);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000834 const ValueDecl *getValueDecl(Expr *Exp);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000835 void warnIfMutexNotHeld (const NamedDecl *D, Expr *Exp, AccessKind AK,
836 MutexID &Mutex, unsigned DiagID);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000837 void checkAccess(Expr *Exp, AccessKind AK);
838 void checkDereference(Expr *Exp, AccessKind AK);
839
840 template <class AttrType>
841 void addLocksToSet(LockKind LK, Attr *Attr, CXXMemberCallExpr *Exp);
842
843 /// \brief Returns true if the lockset contains a lock, regardless of whether
844 /// the lock is held exclusively or shared.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000845 bool locksetContains(MutexID Lock) {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000846 return LSet.lookup(Lock);
847 }
848
849 /// \brief Returns true if the lockset contains a lock with the passed in
850 /// locktype.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000851 bool locksetContains(MutexID Lock, LockKind KindRequested) const {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000852 const LockData *LockHeld = LSet.lookup(Lock);
853 return (LockHeld && KindRequested == LockHeld->LKind);
854 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000855
856public:
857 BuildLockset(Sema &S, Lockset LS, Lockset::Factory &F)
858 : StmtVisitor<BuildLockset>(), S(S), LSet(LS),
859 LocksetFactory(F) {}
860
861 Lockset getLockset() {
862 return LSet;
863 }
864
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000865 void VisitUnaryOperator(UnaryOperator *UO);
866 void VisitBinaryOperator(BinaryOperator *BO);
867 void VisitCastExpr(CastExpr *CE);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000868 void VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp);
869};
870
871/// \brief Add a new lock to the lockset, warning if the lock is already there.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000872/// \param LockLoc The source location of the acquire
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000873/// \param LockExp The lock expression corresponding to the lock to be added
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000874void BuildLockset::addLock(SourceLocation LockLoc, Expr *LockExp,
875 LockKind LK) {
876 // FIXME: deal with acquired before/after annotations
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000877 MutexID Mutex(LockExp);
878 LockData NewLock(LockLoc, LK);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000879
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000880 // FIXME: Don't always warn when we have support for reentrant locks.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000881 if (locksetContains(Mutex))
882 S.Diag(LockLoc, diag::warn_double_lock) << Mutex.getName();
883 LSet = LocksetFactory.add(LSet, Mutex, NewLock);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000884}
885
886/// \brief Remove a lock from the lockset, warning if the lock is not there.
887/// \param LockExp The lock expression corresponding to the lock to be removed
888/// \param UnlockLoc The source location of the unlock (only used in error msg)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +0000889void BuildLockset::removeLock(SourceLocation UnlockLoc, Expr *LockExp) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000890 MutexID Mutex(LockExp);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000891
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000892 Lockset NewLSet = LocksetFactory.remove(LSet, Mutex);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000893 if(NewLSet == LSet)
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000894 S.Diag(UnlockLoc, diag::warn_unlock_but_no_lock) << Mutex.getName();
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000895
896 LSet = NewLSet;
897}
898
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000899/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
900const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
901 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
902 return DR->getDecl();
903
904 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
905 return ME->getMemberDecl();
906
907 return 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +0000908}
909
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000910/// \brief Warn if the LSet does not contain a lock sufficient to protect access
911/// of at least the passed in AccessType.
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000912void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
913 AccessKind AK, MutexID &Mutex,
914 unsigned DiagID) {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000915 switch (AK) {
916 case AK_Read:
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000917 if (!locksetContains(Mutex))
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000918 S.Diag(Exp->getExprLoc(), DiagID)
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000919 << D->getName() << Mutex.getName() << LK_Shared;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000920 break;
921 case AK_Written :
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000922 if (!locksetContains(Mutex, LK_Exclusive))
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000923 S.Diag(Exp->getExprLoc(), DiagID)
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000924 << D->getName() << Mutex.getName() << LK_Exclusive;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000925 break;
926 }
927}
928
929
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000930/// \brief This method identifies variable dereferences and checks pt_guarded_by
931/// and pt_guarded_var annotations. Note that we only check these annotations
932/// at the time a pointer is dereferenced.
933/// FIXME: We need to check for other types of pointer dereferences
934/// (e.g. [], ->) and deal with them here.
935/// \param Exp An expression that has been read or written.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000936void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000937 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
938 if (!UO || UO->getOpcode() != clang::UO_Deref)
939 return;
940 Exp = UO->getSubExpr()->IgnoreParenCasts();
941
942 const ValueDecl *D = getValueDecl(Exp);
943 if(!D || !D->hasAttrs())
944 return;
945
946 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
947 S.Diag(Exp->getExprLoc(), diag::warn_var_deref_requires_any_lock)
948 << D->getName();
949
950 const AttrVec &ArgAttrs = D->getAttrs();
951 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i) {
952 if (ArgAttrs[i]->getKind() != attr::PtGuardedBy)
953 continue;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000954 const PtGuardedByAttr *PGBAttr = cast<PtGuardedByAttr>(ArgAttrs[i]);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000955 MutexID Mutex(PGBAttr->getArg());
956 warnIfMutexNotHeld(D, Exp, AK, Mutex, diag::warn_var_deref_requires_lock);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000957 }
958}
959
960/// \brief Checks guarded_by and guarded_var attributes.
961/// Whenever we identify an access (read or write) of a DeclRefExpr or
962/// MemberExpr, we need to check whether there are any guarded_by or
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000963/// guarded_var attributes, and make sure we hold the appropriate mutexes.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000964void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000965 const ValueDecl *D = getValueDecl(Exp);
966 if(!D || !D->hasAttrs())
967 return;
968
969 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
970 S.Diag(Exp->getExprLoc(), diag::warn_variable_requires_any_lock)
971 << D->getName();
972
973 const AttrVec &ArgAttrs = D->getAttrs();
974 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i) {
975 if (ArgAttrs[i]->getKind() != attr::GuardedBy)
976 continue;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000977 const GuardedByAttr *GBAttr = cast<GuardedByAttr>(ArgAttrs[i]);
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000978 MutexID Mutex(GBAttr->getArg());
979 warnIfMutexNotHeld(D, Exp, AK, Mutex, diag::warn_variable_requires_lock);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000980 }
981}
982
983/// \brief For unary operations which read and write a variable, we need to
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +0000984/// check whether we hold any required mutexes. Reads are checked in
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000985/// VisitCastExpr.
986void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
987 switch (UO->getOpcode()) {
988 case clang::UO_PostDec:
989 case clang::UO_PostInc:
990 case clang::UO_PreDec:
991 case clang::UO_PreInc: {
992 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +0000993 checkAccess(SubExp, AK_Written);
994 checkDereference(SubExp, AK_Written);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +0000995 break;
996 }
997 default:
998 break;
999 }
1000}
1001
1002/// For binary operations which assign to a variable (writes), we need to check
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001003/// whether we hold any required mutexes.
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001004/// FIXME: Deal with non-primitive types.
1005void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1006 if (!BO->isAssignmentOp())
1007 return;
1008 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001009 checkAccess(LHSExp, AK_Written);
1010 checkDereference(LHSExp, AK_Written);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001011}
1012
1013/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001014/// need to ensure we hold any required mutexes.
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001015/// FIXME: Deal with non-primitive types.
1016void BuildLockset::VisitCastExpr(CastExpr *CE) {
1017 if (CE->getCastKind() != CK_LValueToRValue)
1018 return;
1019 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001020 checkAccess(SubExp, AK_Read);
1021 checkDereference(SubExp, AK_Read);
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001022}
1023
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001024/// \brief This function, parameterized by an attribute type, is used to add a
1025/// set of locks specified as attribute arguments to the lockset.
1026template <typename AttrType>
1027void BuildLockset::addLocksToSet(LockKind LK, Attr *Attr,
1028 CXXMemberCallExpr *Exp) {
1029 typedef typename AttrType::args_iterator iterator_type;
1030 SourceLocation ExpLocation = Exp->getExprLoc();
1031 Expr *Parent = Exp->getImplicitObjectArgument();
1032 AttrType *SpecificAttr = cast<AttrType>(Attr);
1033
1034 if (SpecificAttr->args_size() == 0) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001035 // The mutex held is the "this" object.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001036 addLock(ExpLocation, Parent, LK);
1037 return;
1038 }
1039
1040 for (iterator_type I = SpecificAttr->args_begin(),
1041 E = SpecificAttr->args_end(); I != E; ++I)
1042 addLock(ExpLocation, *I, LK);
1043}
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001044
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001045/// \brief When visiting CXXMemberCallExprs we need to examine the attributes on
1046/// the method that is being called and add, remove or check locks in the
1047/// lockset accordingly.
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001048///
Caitlin Sadowski05b436e2011-08-29 22:27:51 +00001049/// FIXME: For classes annotated with one of the guarded annotations, we need
1050/// to treat const method calls as reads and non-const method calls as writes,
1051/// and check that the appropriate locks are held. Non-const method calls with
1052/// the same signature as const method calls can be also treated as reads.
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001053///
1054/// FIXME: We need to also visit CallExprs to catch/check global functions.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001055void BuildLockset::VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001056 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1057
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001058 SourceLocation ExpLocation = Exp->getExprLoc();
1059 Expr *Parent = Exp->getImplicitObjectArgument();
1060
1061 if(!D || !D->hasAttrs())
1062 return;
1063
1064 AttrVec &ArgAttrs = D->getAttrs();
1065 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1066 Attr *Attr = ArgAttrs[i];
1067 switch (Attr->getKind()) {
1068 // When we encounter an exclusive lock function, we need to add the lock
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001069 // to our lockset with kind exclusive.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001070 case attr::ExclusiveLockFunction:
1071 addLocksToSet<ExclusiveLockFunctionAttr>(LK_Exclusive, Attr, Exp);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001072 break;
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001073
1074 // When we encounter a shared lock function, we need to add the lock
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001075 // to our lockset with kind shared.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001076 case attr::SharedLockFunction:
1077 addLocksToSet<SharedLockFunctionAttr>(LK_Shared, Attr, Exp);
1078 break;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001079
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001080 // When we encounter an unlock function, we need to remove unlocked
1081 // mutexes from the lockset, and flag a warning if they are not there.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001082 case attr::UnlockFunction: {
1083 UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
1084
1085 if (UFAttr->args_size() == 0) { // The lock held is the "this" object.
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001086 removeLock(ExpLocation, Parent);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001087 break;
1088 }
1089
1090 for (UnlockFunctionAttr::args_iterator I = UFAttr->args_begin(),
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001091 E = UFAttr->args_end(); I != E; ++I)
Caitlin Sadowski940b97f2011-08-24 18:46:20 +00001092 removeLock(ExpLocation, *I);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001093 break;
1094 }
1095
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001096 case attr::ExclusiveLocksRequired: {
1097 // FIXME: Also use this attribute to add required locks to the initial
1098 // lockset when processing a CFG for a function annotated with this
1099 // attribute.
1100 ExclusiveLocksRequiredAttr *ELRAttr =
1101 cast<ExclusiveLocksRequiredAttr>(Attr);
1102
1103 for (ExclusiveLocksRequiredAttr::args_iterator
1104 I = ELRAttr->args_begin(), E = ELRAttr->args_end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001105 MutexID Mutex(*I);
1106 warnIfMutexNotHeld(D, Exp, AK_Written, Mutex,
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001107 diag::warn_fun_requires_lock);
1108 }
1109 break;
1110 }
1111
1112 case attr::SharedLocksRequired: {
1113 // FIXME: Also use this attribute to add required locks to the initial
1114 // lockset when processing a CFG for a function annotated with this
1115 // attribute.
1116 SharedLocksRequiredAttr *SLRAttr = cast<SharedLocksRequiredAttr>(Attr);
1117
1118 for (SharedLocksRequiredAttr::args_iterator I = SLRAttr->args_begin(),
1119 E = SLRAttr->args_end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001120 MutexID Mutex(*I);
1121 warnIfMutexNotHeld(D, Exp, AK_Read, Mutex,
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001122 diag::warn_fun_requires_lock);
1123 }
1124 break;
1125 }
1126
1127 case attr::LocksExcluded: {
1128 LocksExcludedAttr *LEAttr = cast<LocksExcludedAttr>(Attr);
1129 for (LocksExcludedAttr::args_iterator I = LEAttr->args_begin(),
1130 E = LEAttr->args_end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001131 MutexID Mutex(*I);
1132 if (locksetContains(Mutex))
1133 S.Diag(ExpLocation, diag::warn_fun_excludes_mutex)
1134 << D->getName() << Mutex.getName();
Caitlin Sadowski978191e2011-09-08 18:27:31 +00001135 }
1136 break;
1137 }
1138
1139 case attr::LockReturned:
1140 // FIXME: Deal with this attribute.
1141 break;
1142
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001143 // Ignore other (non thread-safety) attributes
1144 default:
1145 break;
1146 }
1147 }
1148}
1149
1150typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag;
1151typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
1152
1153struct SortDiagBySourceLocation {
1154 Sema &S;
1155
1156 SortDiagBySourceLocation(Sema &S) : S(S) {}
1157
1158 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1159 // Although this call will be slow, this is only called when outputting
1160 // multiple warnings.
1161 return S.getSourceManager().isBeforeInTranslationUnit(left.first,
1162 right.first);
1163 }
1164};
1165} // end anonymous namespace
1166
1167/// \brief Emit all buffered diagnostics in order of sourcelocation.
1168/// We need to output diagnostics produced while iterating through
1169/// the lockset in deterministic order, so this function orders diagnostics
1170/// and outputs them.
1171static void EmitDiagnostics(Sema &S, DiagList &D) {
1172 SortDiagBySourceLocation SortDiagBySL(S);
1173 sort(D.begin(), D.end(), SortDiagBySL);
1174 for (DiagList::iterator I = D.begin(), E = D.end(); I != E; ++I)
1175 S.Diag(I->first, I->second);
1176}
1177
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001178static Lockset warnIfNotInFirstSetOrNotSameKind(Sema &S, const Lockset LSet1,
1179 const Lockset LSet2,
1180 DiagList &Warnings,
1181 Lockset Intersection,
1182 Lockset::Factory &Fact) {
1183 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001184 const MutexID &LSet2Mutex = I.getKey();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001185 const LockData &LSet2LockData = I.getData();
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001186 if (const LockData *LD = LSet1.lookup(LSet2Mutex)) {
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001187 if (LD->LKind != LSet2LockData.LKind) {
1188 PartialDiagnostic Warning =
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001189 S.PDiag(diag::warn_lock_exclusive_and_shared) << LSet2Mutex.getName();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001190 PartialDiagnostic Note =
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001191 S.PDiag(diag::note_lock_exclusive_and_shared) << LSet2Mutex.getName();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001192 Warnings.push_back(DelayedDiag(LSet2LockData.AcquireLoc, Warning));
1193 Warnings.push_back(DelayedDiag(LD->AcquireLoc, Note));
1194 if (LD->LKind != LK_Exclusive)
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001195 Intersection = Fact.add(Intersection, LSet2Mutex, LSet2LockData);
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001196 }
1197 } else {
1198 PartialDiagnostic Warning =
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001199 S.PDiag(diag::warn_lock_at_end_of_scope) << LSet2Mutex.getName();
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001200 Warnings.push_back(DelayedDiag(LSet2LockData.AcquireLoc, Warning));
1201 }
1202 }
1203 return Intersection;
1204}
1205
1206
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001207/// \brief Compute the intersection of two locksets and issue warnings for any
1208/// locks in the symmetric difference.
1209///
1210/// This function is used at a merge point in the CFG when comparing the lockset
1211/// of each branch being merged. For example, given the following sequence:
1212/// A; if () then B; else C; D; we need to check that the lockset after B and C
1213/// are the same. In the event of a difference, we use the intersection of these
1214/// two locksets at the start of D.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001215static Lockset intersectAndWarn(Sema &S, const Lockset LSet1,
1216 const Lockset LSet2,
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001217 Lockset::Factory &Fact) {
1218 Lockset Intersection = LSet1;
1219 DiagList Warnings;
1220
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001221 Intersection = warnIfNotInFirstSetOrNotSameKind(S, LSet1, LSet2, Warnings,
1222 Intersection, Fact);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001223
1224 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
1225 if (!LSet2.contains(I.getKey())) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001226 const MutexID &Mutex = I.getKey();
1227 const LockData &MissingLock = I.getData();
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001228 PartialDiagnostic Warning =
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001229 S.PDiag(diag::warn_lock_at_end_of_scope) << Mutex.getName();
1230 Warnings.push_back(DelayedDiag(MissingLock.AcquireLoc, Warning));
1231 Intersection = Fact.remove(Intersection, Mutex);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001232 }
1233 }
1234
1235 EmitDiagnostics(S, Warnings);
1236 return Intersection;
1237}
1238
1239/// \brief Returns the location of the first Stmt in a Block.
1240static SourceLocation getFirstStmtLocation(CFGBlock *Block) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001241 SourceLocation Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001242 for (CFGBlock::const_iterator BI = Block->begin(), BE = Block->end();
1243 BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001244 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&(*BI))) {
1245 Loc = CfgStmt->getStmt()->getLocStart();
1246 if (Loc.isValid()) return Loc;
1247 }
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001248 }
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001249 if (Stmt *S = Block->getTerminator().getStmt()) {
1250 Loc = S->getLocStart();
1251 if (Loc.isValid()) return Loc;
1252 }
1253 return Loc;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001254}
1255
1256/// \brief Warn about different locksets along backedges of loops.
1257/// This function is called when we encounter a back edge. At that point,
1258/// we need to verify that the lockset before taking the backedge is the
1259/// same as the lockset before entering the loop.
1260///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001261/// \param LoopEntrySet Locks before starting the loop
1262/// \param LoopReentrySet Locks in the last CFG block of the loop
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001263static void warnBackEdgeUnequalLocksets(Sema &S, const Lockset LoopReentrySet,
1264 const Lockset LoopEntrySet,
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001265 SourceLocation FirstLocInLoop,
1266 Lockset::Factory &Fact) {
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001267 assert(FirstLocInLoop.isValid());
1268 DiagList Warnings;
1269
1270 // Warn for locks held at the start of the loop, but not the end.
1271 for (Lockset::iterator I = LoopEntrySet.begin(), E = LoopEntrySet.end();
1272 I != E; ++I) {
1273 if (!LoopReentrySet.contains(I.getKey())) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001274 const MutexID &Mutex = I.getKey();
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001275 // We report this error at the location of the first statement in a loop
1276 PartialDiagnostic Warning =
Caitlin Sadowski179b9202011-09-08 23:17:03 +00001277 S.PDiag(diag::warn_expecting_lock_held_on_loop) << Mutex.getName();
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001278 Warnings.push_back(DelayedDiag(FirstLocInLoop, Warning));
1279 }
1280 }
1281
1282 // Warn for locks held at the end of the loop, but not at the start.
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001283 warnIfNotInFirstSetOrNotSameKind(S, LoopEntrySet, LoopReentrySet, Warnings,
1284 LoopReentrySet, Fact);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001285
1286 EmitDiagnostics(S, Warnings);
1287}
1288
1289/// \brief Check a function's CFG for thread-safety violations.
1290///
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001291/// We traverse the blocks in the CFG, compute the set of mutexes that are held
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001292/// at the end of each block, and issue warnings for thread safety violations.
1293/// Each block in the CFG is traversed exactly once.
1294static void checkThreadSafety(Sema &S, AnalysisContext &AC) {
1295 CFG *CFGraph = AC.getCFG();
1296 if (!CFGraph) return;
Caitlin Sadowskiaf370612011-09-08 18:35:21 +00001297 const Decl *D = AC.getDecl();
1298 if (D && D->getAttr<NoThreadSafetyAnalysisAttr>()) return;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001299
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001300 Lockset::Factory LocksetFactory;
1301
1302 // FIXME: Swith to SmallVector? Otherwise improve performance impact?
1303 std::vector<Lockset> EntryLocksets(CFGraph->getNumBlockIDs(),
1304 LocksetFactory.getEmptyMap());
1305 std::vector<Lockset> ExitLocksets(CFGraph->getNumBlockIDs(),
1306 LocksetFactory.getEmptyMap());
1307
1308 // We need to explore the CFG via a "topological" ordering.
1309 // That way, we will be guaranteed to have information about required
1310 // predecessor locksets when exploring a new block.
1311 TopologicallySortedCFG SortedGraph(CFGraph);
1312 CFGBlockSet VisitedBlocks(CFGraph);
1313
1314 for (TopologicallySortedCFG::iterator I = SortedGraph.begin(),
1315 E = SortedGraph.end(); I!= E; ++I) {
1316 const CFGBlock *CurrBlock = *I;
1317 int CurrBlockID = CurrBlock->getBlockID();
1318
1319 VisitedBlocks.insert(CurrBlock);
1320
1321 // Use the default initial lockset in case there are no predecessors.
1322 Lockset &Entryset = EntryLocksets[CurrBlockID];
1323 Lockset &Exitset = ExitLocksets[CurrBlockID];
1324
1325 // Iterate through the predecessor blocks and warn if the lockset for all
1326 // predecessors is not the same. We take the entry lockset of the current
1327 // block to be the intersection of all previous locksets.
1328 // FIXME: By keeping the intersection, we may output more errors in future
1329 // for a lock which is not in the intersection, but was in the union. We
1330 // may want to also keep the union in future. As an example, let's say
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001331 // the intersection contains Mutex L, and the union contains L and M.
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001332 // Later we unlock M. At this point, we would output an error because we
1333 // never locked M; although the real error is probably that we forgot to
1334 // lock M on all code paths. Conversely, let's say that later we lock M.
1335 // In this case, we should compare against the intersection instead of the
1336 // union because the real error is probably that we forgot to unlock M on
1337 // all code paths.
1338 bool LocksetInitialized = false;
1339 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1340 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1341
1342 // if *PI -> CurrBlock is a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001343 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001344 continue;
1345
1346 int PrevBlockID = (*PI)->getBlockID();
1347 if (!LocksetInitialized) {
1348 Entryset = ExitLocksets[PrevBlockID];
1349 LocksetInitialized = true;
1350 } else {
1351 Entryset = intersectAndWarn(S, Entryset, ExitLocksets[PrevBlockID],
1352 LocksetFactory);
1353 }
1354 }
1355
1356 BuildLockset LocksetBuilder(S, Entryset, LocksetFactory);
1357 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1358 BE = CurrBlock->end(); BI != BE; ++BI) {
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001359 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&*BI))
Ted Kremenekf1d10d92011-08-23 23:05:04 +00001360 LocksetBuilder.Visit(const_cast<Stmt*>(CfgStmt->getStmt()));
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001361 }
1362 Exitset = LocksetBuilder.getLockset();
1363
1364 // For every back edge from CurrBlock (the end of the loop) to another block
1365 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
1366 // the one held at the beginning of FirstLoopBlock. We can look up the
1367 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
1368 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1369 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1370
1371 // if CurrBlock -> *SI is *not* a back edge
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001372 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001373 continue;
1374
1375 CFGBlock *FirstLoopBlock = *SI;
1376 SourceLocation FirstLoopLocation = getFirstStmtLocation(FirstLoopBlock);
1377
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001378 assert(FirstLoopLocation.isValid());
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001379
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001380 // Fail gracefully in release code.
1381 if (!FirstLoopLocation.isValid())
1382 continue;
1383
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001384 Lockset PreLoop = EntryLocksets[FirstLoopBlock->getBlockID()];
1385 Lockset LoopEnd = ExitLocksets[CurrBlockID];
Caitlin Sadowskia53257c2011-09-08 18:19:38 +00001386 warnBackEdgeUnequalLocksets(S, LoopEnd, PreLoop, FirstLoopLocation,
1387 LocksetFactory);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001388 }
1389 }
1390
1391 Lockset FinalLockset = ExitLocksets[CFGraph->getExit().getBlockID()];
1392 if (!FinalLockset.isEmpty()) {
1393 DiagList Warnings;
1394 for (Lockset::iterator I=FinalLockset.begin(), E=FinalLockset.end();
1395 I != E; ++I) {
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001396 const MutexID &Mutex = I.getKey();
1397 const LockData &MissingLock = I.getData();
Caitlin Sadowskib4d0a962011-08-29 17:12:27 +00001398
1399 std::string FunName = "<unknown>";
1400 if (const NamedDecl *ContextDecl = dyn_cast<NamedDecl>(AC.getDecl())) {
1401 FunName = ContextDecl->getDeclName().getAsString();
1402 }
1403
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001404 PartialDiagnostic Warning =
Caitlin Sadowski8bccabe2011-09-08 21:52:50 +00001405 S.PDiag(diag::warn_no_unlock)
1406 << Mutex.getName() << FunName;
1407 Warnings.push_back(DelayedDiag(MissingLock.AcquireLoc, Warning));
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001408 }
1409 EmitDiagnostics(S, Warnings);
1410 }
1411}
1412
1413
Ted Kremenek610068c2011-01-15 02:58:47 +00001414//===----------------------------------------------------------------------===//
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001415// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1416// warnings on a function, method, or block.
1417//===----------------------------------------------------------------------===//
1418
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001419clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1420 enableCheckFallThrough = 1;
1421 enableCheckUnreachable = 0;
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001422 enableThreadSafetyAnalysis = 0;
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001423}
1424
Chandler Carruth5d989942011-07-06 16:21:37 +00001425clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1426 : S(s),
1427 NumFunctionsAnalyzed(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001428 NumFunctionsWithBadCFGs(0),
Chandler Carruth5d989942011-07-06 16:21:37 +00001429 NumCFGBlocks(0),
Benjamin Kramer54cf3412011-07-08 20:38:53 +00001430 MaxCFGBlocksPerFunction(0),
1431 NumUninitAnalysisFunctions(0),
1432 NumUninitAnalysisVariables(0),
1433 MaxUninitAnalysisVariablesPerFunction(0),
1434 NumUninitAnalysisBlockVisits(0),
1435 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001436 Diagnostic &D = S.getDiagnostics();
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001437 DefaultPolicy.enableCheckUnreachable = (unsigned)
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00001438 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
1439 Diagnostic::Ignored);
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001440 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
1441 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
1442 Diagnostic::Ignored);
1443
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001444}
1445
Ted Kremenek351ba912011-02-23 01:52:04 +00001446static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001447 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek351ba912011-02-23 01:52:04 +00001448 i = fscope->PossiblyUnreachableDiags.begin(),
1449 e = fscope->PossiblyUnreachableDiags.end();
1450 i != e; ++i) {
1451 const sema::PossiblyUnreachableDiag &D = *i;
1452 S.Diag(D.Loc, D.PD);
1453 }
1454}
1455
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001456void clang::sema::
1457AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenek283a3582011-02-23 01:51:53 +00001458 sema::FunctionScopeInfo *fscope,
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001459 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekd068aab2010-03-20 21:11:09 +00001460
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001461 // We avoid doing analysis-based warnings when there are errors for
1462 // two reasons:
1463 // (1) The CFGs often can't be constructed (if the body is invalid), so
1464 // don't bother trying.
1465 // (2) The code already has problems; running the analysis just takes more
1466 // time.
Ted Kremenek99e81922010-04-30 21:49:25 +00001467 Diagnostic &Diags = S.getDiagnostics();
1468
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001469 // Do not do any analysis for declarations in system headers if we are
1470 // going to just ignore them.
Ted Kremenek99e81922010-04-30 21:49:25 +00001471 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001472 S.SourceMgr.isInSystemHeader(D->getLocation()))
1473 return;
1474
John McCalle0054f62010-08-25 05:56:39 +00001475 // For code in dependent contexts, we'll do this at instantiation time.
1476 if (cast<DeclContext>(D)->isDependentContext())
1477 return;
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001478
Ted Kremenek351ba912011-02-23 01:52:04 +00001479 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
1480 // Flush out any possibly unreachable diagnostics.
1481 flushDiagnostics(S, fscope);
1482 return;
1483 }
1484
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001485 const Stmt *Body = D->getBody();
1486 assert(Body);
1487
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001488 AnalysisContext AC(D, 0);
1489
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001490 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
1491 // explosion for destrutors that can result and the compile time hit.
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001492 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1493 AC.getCFGBuildOptions().AddEHEdges = false;
1494 AC.getCFGBuildOptions().AddInitializers = true;
1495 AC.getCFGBuildOptions().AddImplicitDtors = true;
Ted Kremenek0c8e5a02011-07-19 14:18:48 +00001496
1497 // Force that certain expressions appear as CFGElements in the CFG. This
1498 // is used to speed up various analyses.
1499 // FIXME: This isn't the right factoring. This is here for initial
1500 // prototyping, but we need a way for analyses to say what expressions they
1501 // expect to always be CFGElements and then fill in the BuildOptions
1502 // appropriately. This is essentially a layering violation.
Ted Kremenek0f3b4ca2011-08-23 23:05:11 +00001503 if (P.enableCheckUnreachable) {
1504 // Unreachable code analysis requires a linearized CFG.
1505 AC.getCFGBuildOptions().setAllAlwaysAdd();
1506 }
1507 else {
1508 AC.getCFGBuildOptions()
1509 .setAlwaysAdd(Stmt::BinaryOperatorClass)
1510 .setAlwaysAdd(Stmt::BlockExprClass)
1511 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1512 .setAlwaysAdd(Stmt::DeclRefExprClass)
1513 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
1514 .setAlwaysAdd(Stmt::UnaryOperatorClass);
1515 }
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001516
Ted Kremenekbc5cb8a2011-07-21 05:22:47 +00001517 // Construct the analysis context with the specified CFG build options.
1518
Ted Kremenek351ba912011-02-23 01:52:04 +00001519 // Emit delayed diagnostics.
1520 if (!fscope->PossiblyUnreachableDiags.empty()) {
1521 bool analyzed = false;
Ted Kremenek0d28d362011-03-10 03:50:34 +00001522
1523 // Register the expressions with the CFGBuilder.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001524 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001525 i = fscope->PossiblyUnreachableDiags.begin(),
1526 e = fscope->PossiblyUnreachableDiags.end();
1527 i != e; ++i) {
1528 if (const Stmt *stmt = i->stmt)
1529 AC.registerForcedBlockExpression(stmt);
1530 }
1531
1532 if (AC.getCFG()) {
1533 analyzed = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001534 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek0d28d362011-03-10 03:50:34 +00001535 i = fscope->PossiblyUnreachableDiags.begin(),
1536 e = fscope->PossiblyUnreachableDiags.end();
1537 i != e; ++i)
1538 {
1539 const sema::PossiblyUnreachableDiag &D = *i;
1540 bool processed = false;
1541 if (const Stmt *stmt = i->stmt) {
1542 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
1543 assert(block);
Ted Kremenekaf13d5b2011-03-19 01:00:33 +00001544 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) {
Ted Kremenek351ba912011-02-23 01:52:04 +00001545 // Can this block be reached from the entrance?
Ted Kremenek0d28d362011-03-10 03:50:34 +00001546 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek351ba912011-02-23 01:52:04 +00001547 S.Diag(D.Loc, D.PD);
Ted Kremenek0d28d362011-03-10 03:50:34 +00001548 processed = true;
Ted Kremenek351ba912011-02-23 01:52:04 +00001549 }
1550 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001551 if (!processed) {
1552 // Emit the warning anyway if we cannot map to a basic block.
1553 S.Diag(D.Loc, D.PD);
1554 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001555 }
Ted Kremenek0d28d362011-03-10 03:50:34 +00001556 }
Ted Kremenek351ba912011-02-23 01:52:04 +00001557
1558 if (!analyzed)
1559 flushDiagnostics(S, fscope);
1560 }
1561
1562
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001563 // Warning: check missing 'return'
Ted Kremenekd064fdc2010-03-23 00:13:23 +00001564 if (P.enableCheckFallThrough) {
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001565 const CheckFallThroughDiagnostics &CD =
1566 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorca7eaee2010-04-16 23:28:44 +00001567 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek3ed6fc02011-02-23 01:51:48 +00001568 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001569 }
1570
1571 // Warning: check for unreachable code
Ted Kremenekb7e5f142010-04-08 18:51:44 +00001572 if (P.enableCheckUnreachable)
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001573 CheckUnreachable(S, AC);
Ted Kremenek610068c2011-01-15 02:58:47 +00001574
Caitlin Sadowski3ac1fbc2011-08-23 18:46:34 +00001575 // Check for thread safety violations
1576 if (P.enableThreadSafetyAnalysis)
1577 checkThreadSafety(S, AC);
1578
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001579 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
Ted Kremenek76709bf2011-03-15 05:22:28 +00001580 != Diagnostic::Ignored ||
1581 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
Ted Kremenek610068c2011-01-15 02:58:47 +00001582 != Diagnostic::Ignored) {
Ted Kremenekc5e43c12011-03-17 05:29:57 +00001583 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekc21fed32011-01-18 21:18:58 +00001584 UninitValsDiagReporter reporter(S);
Fariborz Jahanian57080fb2011-07-16 18:31:33 +00001585 UninitVariablesAnalysisStats stats;
Benjamin Kramer12efd572011-07-16 20:13:06 +00001586 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremeneka8c17a52011-01-25 19:13:48 +00001587 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruth5d989942011-07-06 16:21:37 +00001588 reporter, stats);
1589
1590 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1591 ++NumUninitAnalysisFunctions;
1592 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1593 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1594 MaxUninitAnalysisVariablesPerFunction =
1595 std::max(MaxUninitAnalysisVariablesPerFunction,
1596 stats.NumVariablesAnalyzed);
1597 MaxUninitAnalysisBlockVisitsPerFunction =
1598 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1599 stats.NumBlockVisits);
1600 }
Ted Kremenek610068c2011-01-15 02:58:47 +00001601 }
1602 }
Chandler Carruth5d989942011-07-06 16:21:37 +00001603
1604 // Collect statistics about the CFG if it was built.
1605 if (S.CollectStats && AC.isCFGBuilt()) {
1606 ++NumFunctionsAnalyzed;
1607 if (CFG *cfg = AC.getCFG()) {
1608 // If we successfully built a CFG for this context, record some more
1609 // detail information about it.
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001610 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruth5d989942011-07-06 16:21:37 +00001611 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth3ea4c492011-07-06 22:21:45 +00001612 cfg->getNumBlockIDs());
Chandler Carruth5d989942011-07-06 16:21:37 +00001613 } else {
1614 ++NumFunctionsWithBadCFGs;
1615 }
1616 }
1617}
1618
1619void clang::sema::AnalysisBasedWarnings::PrintStats() const {
1620 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
1621
1622 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
1623 unsigned AvgCFGBlocksPerFunction =
1624 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
1625 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
1626 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
1627 << " " << NumCFGBlocks << " CFG blocks built.\n"
1628 << " " << AvgCFGBlocksPerFunction
1629 << " average CFG blocks per function.\n"
1630 << " " << MaxCFGBlocksPerFunction
1631 << " max CFG blocks per function.\n";
1632
1633 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
1634 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
1635 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
1636 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
1637 llvm::errs() << NumUninitAnalysisFunctions
1638 << " functions analyzed for uninitialiazed variables\n"
1639 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
1640 << " " << AvgUninitVariablesPerFunction
1641 << " average variables per function.\n"
1642 << " " << MaxUninitAnalysisVariablesPerFunction
1643 << " max variables per function.\n"
1644 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
1645 << " " << AvgUninitBlockVisitsPerFunction
1646 << " average block visits per function.\n"
1647 << " " << MaxUninitAnalysisBlockVisitsPerFunction
1648 << " max block visits per function.\n";
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00001649}