AnalysisBasedWarnings.cpp revision 99ba9e3bd70671f3441fb974895f226a83ce0e66
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/Sema/SemaInternal.h" 18#include "clang/Sema/ScopeInfo.h" 19#include "clang/Basic/SourceManager.h" 20#include "clang/Basic/SourceLocation.h" 21#include "clang/Lex/Preprocessor.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/DeclCXX.h" 24#include "clang/AST/ExprObjC.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/StmtObjC.h" 27#include "clang/AST/StmtCXX.h" 28#include "clang/AST/EvaluatedExprVisitor.h" 29#include "clang/AST/StmtVisitor.h" 30#include "clang/Analysis/AnalysisContext.h" 31#include "clang/Analysis/CFG.h" 32#include "clang/Analysis/Analyses/ReachableCode.h" 33#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h" 34#include "clang/Analysis/Analyses/ThreadSafety.h" 35#include "clang/Analysis/CFGStmtMap.h" 36#include "clang/Analysis/Analyses/UninitializedValues.h" 37#include "llvm/ADT/BitVector.h" 38#include "llvm/ADT/FoldingSet.h" 39#include "llvm/ADT/ImmutableMap.h" 40#include "llvm/ADT/PostOrderIterator.h" 41#include "llvm/ADT/SmallVector.h" 42#include "llvm/ADT/StringRef.h" 43#include "llvm/Support/Casting.h" 44#include <algorithm> 45#include <vector> 46 47using namespace clang; 48 49//===----------------------------------------------------------------------===// 50// Unreachable code analysis. 51//===----------------------------------------------------------------------===// 52 53namespace { 54 class UnreachableCodeHandler : public reachable_code::Callback { 55 Sema &S; 56 public: 57 UnreachableCodeHandler(Sema &s) : S(s) {} 58 59 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) { 60 S.Diag(L, diag::warn_unreachable) << R1 << R2; 61 } 62 }; 63} 64 65/// CheckUnreachable - Check for unreachable code. 66static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) { 67 UnreachableCodeHandler UC(S); 68 reachable_code::FindUnreachableCode(AC, UC); 69} 70 71//===----------------------------------------------------------------------===// 72// Check for missing return value. 73//===----------------------------------------------------------------------===// 74 75enum ControlFlowKind { 76 UnknownFallThrough, 77 NeverFallThrough, 78 MaybeFallThrough, 79 AlwaysFallThrough, 80 NeverFallThroughOrReturn 81}; 82 83/// CheckFallThrough - Check that we don't fall off the end of a 84/// Statement that should return a value. 85/// 86/// \returns AlwaysFallThrough iff we always fall off the end of the statement, 87/// MaybeFallThrough iff we might or might not fall off the end, 88/// NeverFallThroughOrReturn iff we never fall off the end of the statement or 89/// return. We assume NeverFallThrough iff we never fall off the end of the 90/// statement but we may return. We assume that functions not marked noreturn 91/// will return. 92static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) { 93 CFG *cfg = AC.getCFG(); 94 if (cfg == 0) return UnknownFallThrough; 95 96 // The CFG leaves in dead things, and we don't want the dead code paths to 97 // confuse us, so we mark all live things first. 98 llvm::BitVector live(cfg->getNumBlockIDs()); 99 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(), 100 live); 101 102 bool AddEHEdges = AC.getAddEHEdges(); 103 if (!AddEHEdges && count != cfg->getNumBlockIDs()) 104 // When there are things remaining dead, and we didn't add EH edges 105 // from CallExprs to the catch clauses, we have to go back and 106 // mark them as live. 107 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) { 108 CFGBlock &b = **I; 109 if (!live[b.getBlockID()]) { 110 if (b.pred_begin() == b.pred_end()) { 111 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator())) 112 // When not adding EH edges from calls, catch clauses 113 // can otherwise seem dead. Avoid noting them as dead. 114 count += reachable_code::ScanReachableFromBlock(&b, live); 115 continue; 116 } 117 } 118 } 119 120 // Now we know what is live, we check the live precessors of the exit block 121 // and look for fall through paths, being careful to ignore normal returns, 122 // and exceptional paths. 123 bool HasLiveReturn = false; 124 bool HasFakeEdge = false; 125 bool HasPlainEdge = false; 126 bool HasAbnormalEdge = false; 127 128 // Ignore default cases that aren't likely to be reachable because all 129 // enums in a switch(X) have explicit case statements. 130 CFGBlock::FilterOptions FO; 131 FO.IgnoreDefaultsWithCoveredEnums = 1; 132 133 for (CFGBlock::filtered_pred_iterator 134 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) { 135 const CFGBlock& B = **I; 136 if (!live[B.getBlockID()]) 137 continue; 138 139 // Skip blocks which contain an element marked as no-return. They don't 140 // represent actually viable edges into the exit block, so mark them as 141 // abnormal. 142 if (B.hasNoReturnElement()) { 143 HasAbnormalEdge = true; 144 continue; 145 } 146 147 // Destructors can appear after the 'return' in the CFG. This is 148 // normal. We need to look pass the destructors for the return 149 // statement (if it exists). 150 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend(); 151 152 for ( ; ri != re ; ++ri) 153 if (isa<CFGStmt>(*ri)) 154 break; 155 156 // No more CFGElements in the block? 157 if (ri == re) { 158 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) { 159 HasAbnormalEdge = true; 160 continue; 161 } 162 // A labeled empty statement, or the entry block... 163 HasPlainEdge = true; 164 continue; 165 } 166 167 CFGStmt CS = cast<CFGStmt>(*ri); 168 const Stmt *S = CS.getStmt(); 169 if (isa<ReturnStmt>(S)) { 170 HasLiveReturn = true; 171 continue; 172 } 173 if (isa<ObjCAtThrowStmt>(S)) { 174 HasFakeEdge = true; 175 continue; 176 } 177 if (isa<CXXThrowExpr>(S)) { 178 HasFakeEdge = true; 179 continue; 180 } 181 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) { 182 if (AS->isMSAsm()) { 183 HasFakeEdge = true; 184 HasLiveReturn = true; 185 continue; 186 } 187 } 188 if (isa<CXXTryStmt>(S)) { 189 HasAbnormalEdge = true; 190 continue; 191 } 192 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit()) 193 == B.succ_end()) { 194 HasAbnormalEdge = true; 195 continue; 196 } 197 198 HasPlainEdge = true; 199 } 200 if (!HasPlainEdge) { 201 if (HasLiveReturn) 202 return NeverFallThrough; 203 return NeverFallThroughOrReturn; 204 } 205 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn) 206 return MaybeFallThrough; 207 // This says AlwaysFallThrough for calls to functions that are not marked 208 // noreturn, that don't return. If people would like this warning to be more 209 // accurate, such functions should be marked as noreturn. 210 return AlwaysFallThrough; 211} 212 213namespace { 214 215struct CheckFallThroughDiagnostics { 216 unsigned diag_MaybeFallThrough_HasNoReturn; 217 unsigned diag_MaybeFallThrough_ReturnsNonVoid; 218 unsigned diag_AlwaysFallThrough_HasNoReturn; 219 unsigned diag_AlwaysFallThrough_ReturnsNonVoid; 220 unsigned diag_NeverFallThroughOrReturn; 221 bool funMode; 222 SourceLocation FuncLoc; 223 224 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) { 225 CheckFallThroughDiagnostics D; 226 D.FuncLoc = Func->getLocation(); 227 D.diag_MaybeFallThrough_HasNoReturn = 228 diag::warn_falloff_noreturn_function; 229 D.diag_MaybeFallThrough_ReturnsNonVoid = 230 diag::warn_maybe_falloff_nonvoid_function; 231 D.diag_AlwaysFallThrough_HasNoReturn = 232 diag::warn_falloff_noreturn_function; 233 D.diag_AlwaysFallThrough_ReturnsNonVoid = 234 diag::warn_falloff_nonvoid_function; 235 236 // Don't suggest that virtual functions be marked "noreturn", since they 237 // might be overridden by non-noreturn functions. 238 bool isVirtualMethod = false; 239 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func)) 240 isVirtualMethod = Method->isVirtual(); 241 242 // Don't suggest that template instantiations be marked "noreturn" 243 bool isTemplateInstantiation = false; 244 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func)) 245 isTemplateInstantiation = Function->isTemplateInstantiation(); 246 247 if (!isVirtualMethod && !isTemplateInstantiation) 248 D.diag_NeverFallThroughOrReturn = 249 diag::warn_suggest_noreturn_function; 250 else 251 D.diag_NeverFallThroughOrReturn = 0; 252 253 D.funMode = true; 254 return D; 255 } 256 257 static CheckFallThroughDiagnostics MakeForBlock() { 258 CheckFallThroughDiagnostics D; 259 D.diag_MaybeFallThrough_HasNoReturn = 260 diag::err_noreturn_block_has_return_expr; 261 D.diag_MaybeFallThrough_ReturnsNonVoid = 262 diag::err_maybe_falloff_nonvoid_block; 263 D.diag_AlwaysFallThrough_HasNoReturn = 264 diag::err_noreturn_block_has_return_expr; 265 D.diag_AlwaysFallThrough_ReturnsNonVoid = 266 diag::err_falloff_nonvoid_block; 267 D.diag_NeverFallThroughOrReturn = 268 diag::warn_suggest_noreturn_block; 269 D.funMode = false; 270 return D; 271 } 272 273 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid, 274 bool HasNoReturn) const { 275 if (funMode) { 276 return (ReturnsVoid || 277 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function, 278 FuncLoc) == DiagnosticsEngine::Ignored) 279 && (!HasNoReturn || 280 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr, 281 FuncLoc) == DiagnosticsEngine::Ignored) 282 && (!ReturnsVoid || 283 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc) 284 == DiagnosticsEngine::Ignored); 285 } 286 287 // For blocks. 288 return ReturnsVoid && !HasNoReturn 289 && (!ReturnsVoid || 290 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc) 291 == DiagnosticsEngine::Ignored); 292 } 293}; 294 295} 296 297/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a 298/// function that should return a value. Check that we don't fall off the end 299/// of a noreturn function. We assume that functions and blocks not marked 300/// noreturn will return. 301static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, 302 const BlockExpr *blkExpr, 303 const CheckFallThroughDiagnostics& CD, 304 AnalysisDeclContext &AC) { 305 306 bool ReturnsVoid = false; 307 bool HasNoReturn = false; 308 309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 310 ReturnsVoid = FD->getResultType()->isVoidType(); 311 HasNoReturn = FD->hasAttr<NoReturnAttr>() || 312 FD->getType()->getAs<FunctionType>()->getNoReturnAttr(); 313 } 314 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 315 ReturnsVoid = MD->getResultType()->isVoidType(); 316 HasNoReturn = MD->hasAttr<NoReturnAttr>(); 317 } 318 else if (isa<BlockDecl>(D)) { 319 QualType BlockTy = blkExpr->getType(); 320 if (const FunctionType *FT = 321 BlockTy->getPointeeType()->getAs<FunctionType>()) { 322 if (FT->getResultType()->isVoidType()) 323 ReturnsVoid = true; 324 if (FT->getNoReturnAttr()) 325 HasNoReturn = true; 326 } 327 } 328 329 DiagnosticsEngine &Diags = S.getDiagnostics(); 330 331 // Short circuit for compilation speed. 332 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn)) 333 return; 334 335 // FIXME: Function try block 336 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) { 337 switch (CheckFallThrough(AC)) { 338 case UnknownFallThrough: 339 break; 340 341 case MaybeFallThrough: 342 if (HasNoReturn) 343 S.Diag(Compound->getRBracLoc(), 344 CD.diag_MaybeFallThrough_HasNoReturn); 345 else if (!ReturnsVoid) 346 S.Diag(Compound->getRBracLoc(), 347 CD.diag_MaybeFallThrough_ReturnsNonVoid); 348 break; 349 case AlwaysFallThrough: 350 if (HasNoReturn) 351 S.Diag(Compound->getRBracLoc(), 352 CD.diag_AlwaysFallThrough_HasNoReturn); 353 else if (!ReturnsVoid) 354 S.Diag(Compound->getRBracLoc(), 355 CD.diag_AlwaysFallThrough_ReturnsNonVoid); 356 break; 357 case NeverFallThroughOrReturn: 358 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) { 359 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 360 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn) 361 << 0 << FD; 362 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 363 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn) 364 << 1 << MD; 365 } else { 366 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn); 367 } 368 } 369 break; 370 case NeverFallThrough: 371 break; 372 } 373 } 374} 375 376//===----------------------------------------------------------------------===// 377// -Wuninitialized 378//===----------------------------------------------------------------------===// 379 380namespace { 381/// ContainsReference - A visitor class to search for references to 382/// a particular declaration (the needle) within any evaluated component of an 383/// expression (recursively). 384class ContainsReference : public EvaluatedExprVisitor<ContainsReference> { 385 bool FoundReference; 386 const DeclRefExpr *Needle; 387 388public: 389 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle) 390 : EvaluatedExprVisitor<ContainsReference>(Context), 391 FoundReference(false), Needle(Needle) {} 392 393 void VisitExpr(Expr *E) { 394 // Stop evaluating if we already have a reference. 395 if (FoundReference) 396 return; 397 398 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E); 399 } 400 401 void VisitDeclRefExpr(DeclRefExpr *E) { 402 if (E == Needle) 403 FoundReference = true; 404 else 405 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E); 406 } 407 408 bool doesContainReference() const { return FoundReference; } 409}; 410} 411 412static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) { 413 // Don't issue a fixit if there is already an initializer. 414 if (VD->getInit()) 415 return false; 416 417 // Suggest possible initialization (if any). 418 const char *initialization = 0; 419 QualType VariableTy = VD->getType().getCanonicalType(); 420 421 if (VariableTy->isObjCObjectPointerType() || 422 VariableTy->isBlockPointerType()) { 423 // Check if 'nil' is defined. 424 if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("nil"))) 425 initialization = " = nil"; 426 else 427 initialization = " = 0"; 428 } 429 else if (VariableTy->isRealFloatingType()) 430 initialization = " = 0.0"; 431 else if (VariableTy->isBooleanType() && S.Context.getLangOptions().CPlusPlus) 432 initialization = " = false"; 433 else if (VariableTy->isEnumeralType()) 434 return false; 435 else if (VariableTy->isPointerType() || VariableTy->isMemberPointerType()) { 436 if (S.Context.getLangOptions().CPlusPlus0x) 437 initialization = " = nullptr"; 438 // Check if 'NULL' is defined. 439 else if (S.PP.getMacroInfo(&S.getASTContext().Idents.get("NULL"))) 440 initialization = " = NULL"; 441 else 442 initialization = " = 0"; 443 } 444 else if (VariableTy->isScalarType()) 445 initialization = " = 0"; 446 447 if (initialization) { 448 SourceLocation loc = S.PP.getLocForEndOfToken(VD->getLocEnd()); 449 S.Diag(loc, diag::note_var_fixit_add_initialization) << VD->getDeclName() 450 << FixItHint::CreateInsertion(loc, initialization); 451 return true; 452 } 453 return false; 454} 455 456/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an 457/// uninitialized variable. This manages the different forms of diagnostic 458/// emitted for particular types of uses. Returns true if the use was diagnosed 459/// as a warning. If a pariticular use is one we omit warnings for, returns 460/// false. 461static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, 462 const Expr *E, bool isAlwaysUninit, 463 bool alwaysReportSelfInit = false) { 464 bool isSelfInit = false; 465 466 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 467 if (isAlwaysUninit) { 468 // Inspect the initializer of the variable declaration which is 469 // being referenced prior to its initialization. We emit 470 // specialized diagnostics for self-initialization, and we 471 // specifically avoid warning about self references which take the 472 // form of: 473 // 474 // int x = x; 475 // 476 // This is used to indicate to GCC that 'x' is intentionally left 477 // uninitialized. Proven code paths which access 'x' in 478 // an uninitialized state after this will still warn. 479 // 480 // TODO: Should we suppress maybe-uninitialized warnings for 481 // variables initialized in this way? 482 if (const Expr *Initializer = VD->getInit()) { 483 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts()) 484 return false; 485 486 ContainsReference CR(S.Context, DRE); 487 CR.Visit(const_cast<Expr*>(Initializer)); 488 isSelfInit = CR.doesContainReference(); 489 } 490 if (isSelfInit) { 491 S.Diag(DRE->getLocStart(), 492 diag::warn_uninit_self_reference_in_init) 493 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange(); 494 } else { 495 S.Diag(DRE->getLocStart(), diag::warn_uninit_var) 496 << VD->getDeclName() << DRE->getSourceRange(); 497 } 498 } else { 499 S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var) 500 << VD->getDeclName() << DRE->getSourceRange(); 501 } 502 } else { 503 const BlockExpr *BE = cast<BlockExpr>(E); 504 S.Diag(BE->getLocStart(), 505 isAlwaysUninit ? diag::warn_uninit_var_captured_by_block 506 : diag::warn_maybe_uninit_var_captured_by_block) 507 << VD->getDeclName(); 508 } 509 510 // Report where the variable was declared when the use wasn't within 511 // the initializer of that declaration & we didn't already suggest 512 // an initialization fixit. 513 if (!isSelfInit && !SuggestInitializationFixit(S, VD)) 514 S.Diag(VD->getLocStart(), diag::note_uninit_var_def) 515 << VD->getDeclName(); 516 517 return true; 518} 519 520typedef std::pair<const Expr*, bool> UninitUse; 521 522namespace { 523struct SLocSort { 524 bool operator()(const UninitUse &a, const UninitUse &b) { 525 SourceLocation aLoc = a.first->getLocStart(); 526 SourceLocation bLoc = b.first->getLocStart(); 527 return aLoc.getRawEncoding() < bLoc.getRawEncoding(); 528 } 529}; 530 531class UninitValsDiagReporter : public UninitVariablesHandler { 532 Sema &S; 533 typedef SmallVector<UninitUse, 2> UsesVec; 534 typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap; 535 UsesMap *uses; 536 537public: 538 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {} 539 ~UninitValsDiagReporter() { 540 flushDiagnostics(); 541 } 542 543 std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) { 544 if (!uses) 545 uses = new UsesMap(); 546 547 UsesMap::mapped_type &V = (*uses)[vd]; 548 UsesVec *&vec = V.first; 549 if (!vec) 550 vec = new UsesVec(); 551 552 return V; 553 } 554 555 void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd, 556 bool isAlwaysUninit) { 557 getUses(vd).first->push_back(std::make_pair(ex, isAlwaysUninit)); 558 } 559 560 void handleSelfInit(const VarDecl *vd) { 561 getUses(vd).second = true; 562 } 563 564 void flushDiagnostics() { 565 if (!uses) 566 return; 567 568 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) { 569 const VarDecl *vd = i->first; 570 const UsesMap::mapped_type &V = i->second; 571 572 UsesVec *vec = V.first; 573 bool hasSelfInit = V.second; 574 575 // Specially handle the case where we have uses of an uninitialized 576 // variable, but the root cause is an idiomatic self-init. We want 577 // to report the diagnostic at the self-init since that is the root cause. 578 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec)) 579 DiagnoseUninitializedUse(S, vd, vd->getInit()->IgnoreParenCasts(), 580 /* isAlwaysUninit */ true, 581 /* alwaysReportSelfInit */ true); 582 else { 583 // Sort the uses by their SourceLocations. While not strictly 584 // guaranteed to produce them in line/column order, this will provide 585 // a stable ordering. 586 std::sort(vec->begin(), vec->end(), SLocSort()); 587 588 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve; 589 ++vi) { 590 if (DiagnoseUninitializedUse(S, vd, vi->first, 591 /*isAlwaysUninit=*/vi->second)) 592 // Skip further diagnostics for this variable. We try to warn only 593 // on the first point at which a variable is used uninitialized. 594 break; 595 } 596 } 597 598 // Release the uses vector. 599 delete vec; 600 } 601 delete uses; 602 } 603 604private: 605 static bool hasAlwaysUninitializedUse(const UsesVec* vec) { 606 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) { 607 if (i->second) { 608 return true; 609 } 610 } 611 return false; 612} 613}; 614} 615 616 617//===----------------------------------------------------------------------===// 618// -Wthread-safety 619//===----------------------------------------------------------------------===// 620namespace clang { 621namespace thread_safety { 622typedef std::pair<SourceLocation, PartialDiagnostic> DelayedDiag; 623typedef llvm::SmallVector<DelayedDiag, 4> DiagList; 624 625struct SortDiagBySourceLocation { 626 Sema &S; 627 SortDiagBySourceLocation(Sema &S) : S(S) {} 628 629 bool operator()(const DelayedDiag &left, const DelayedDiag &right) { 630 // Although this call will be slow, this is only called when outputting 631 // multiple warnings. 632 return S.getSourceManager().isBeforeInTranslationUnit(left.first, 633 right.first); 634 } 635}; 636 637namespace { 638class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler { 639 Sema &S; 640 DiagList Warnings; 641 SourceLocation FunLocation; 642 643 // Helper functions 644 void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) { 645 // Gracefully handle rare cases when the analysis can't get a more 646 // precise source location. 647 if (!Loc.isValid()) 648 Loc = FunLocation; 649 PartialDiagnostic Warning = S.PDiag(DiagID) << LockName; 650 Warnings.push_back(DelayedDiag(Loc, Warning)); 651 } 652 653 public: 654 ThreadSafetyReporter(Sema &S, SourceLocation FL) 655 : S(S), FunLocation(FL) {} 656 657 /// \brief Emit all buffered diagnostics in order of sourcelocation. 658 /// We need to output diagnostics produced while iterating through 659 /// the lockset in deterministic order, so this function orders diagnostics 660 /// and outputs them. 661 void emitDiagnostics() { 662 SortDiagBySourceLocation SortDiagBySL(S); 663 sort(Warnings.begin(), Warnings.end(), SortDiagBySL); 664 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end(); 665 I != E; ++I) 666 S.Diag(I->first, I->second); 667 } 668 669 void handleInvalidLockExp(SourceLocation Loc) { 670 PartialDiagnostic Warning = S.PDiag(diag::warn_cannot_resolve_lock) << Loc; 671 Warnings.push_back(DelayedDiag(Loc, Warning)); 672 } 673 void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) { 674 warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc); 675 } 676 677 void handleDoubleLock(Name LockName, SourceLocation Loc) { 678 warnLockMismatch(diag::warn_double_lock, LockName, Loc); 679 } 680 681 void handleMutexHeldEndOfScope(Name LockName, SourceLocation Loc, 682 LockErrorKind LEK){ 683 unsigned DiagID = 0; 684 switch (LEK) { 685 case LEK_LockedSomePredecessors: 686 DiagID = diag::warn_lock_at_end_of_scope; 687 break; 688 case LEK_LockedSomeLoopIterations: 689 DiagID = diag::warn_expecting_lock_held_on_loop; 690 break; 691 case LEK_LockedAtEndOfFunction: 692 DiagID = diag::warn_no_unlock; 693 break; 694 } 695 warnLockMismatch(DiagID, LockName, Loc); 696 } 697 698 699 void handleExclusiveAndShared(Name LockName, SourceLocation Loc1, 700 SourceLocation Loc2) { 701 PartialDiagnostic Warning = 702 S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName; 703 PartialDiagnostic Note = 704 S.PDiag(diag::note_lock_exclusive_and_shared) << LockName; 705 Warnings.push_back(DelayedDiag(Loc1, Warning)); 706 Warnings.push_back(DelayedDiag(Loc2, Note)); 707 } 708 709 void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK, 710 AccessKind AK, SourceLocation Loc) { 711 assert((POK == POK_VarAccess || POK == POK_VarDereference) 712 && "Only works for variables"); 713 unsigned DiagID = POK == POK_VarAccess? 714 diag::warn_variable_requires_any_lock: 715 diag::warn_var_deref_requires_any_lock; 716 PartialDiagnostic Warning = S.PDiag(DiagID) 717 << D->getName() << getLockKindFromAccessKind(AK); 718 Warnings.push_back(DelayedDiag(Loc, Warning)); 719 } 720 721 void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK, 722 Name LockName, LockKind LK, SourceLocation Loc) { 723 unsigned DiagID = 0; 724 switch (POK) { 725 case POK_VarAccess: 726 DiagID = diag::warn_variable_requires_lock; 727 break; 728 case POK_VarDereference: 729 DiagID = diag::warn_var_deref_requires_lock; 730 break; 731 case POK_FunctionCall: 732 DiagID = diag::warn_fun_requires_lock; 733 break; 734 } 735 PartialDiagnostic Warning = S.PDiag(DiagID) 736 << D->getName() << LockName << LK; 737 Warnings.push_back(DelayedDiag(Loc, Warning)); 738 } 739 740 void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) { 741 PartialDiagnostic Warning = 742 S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName; 743 Warnings.push_back(DelayedDiag(Loc, Warning)); 744 } 745}; 746} 747} 748} 749 750//===----------------------------------------------------------------------===// 751// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based 752// warnings on a function, method, or block. 753//===----------------------------------------------------------------------===// 754 755clang::sema::AnalysisBasedWarnings::Policy::Policy() { 756 enableCheckFallThrough = 1; 757 enableCheckUnreachable = 0; 758 enableThreadSafetyAnalysis = 0; 759} 760 761clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s) 762 : S(s), 763 NumFunctionsAnalyzed(0), 764 NumFunctionsWithBadCFGs(0), 765 NumCFGBlocks(0), 766 MaxCFGBlocksPerFunction(0), 767 NumUninitAnalysisFunctions(0), 768 NumUninitAnalysisVariables(0), 769 MaxUninitAnalysisVariablesPerFunction(0), 770 NumUninitAnalysisBlockVisits(0), 771 MaxUninitAnalysisBlockVisitsPerFunction(0) { 772 DiagnosticsEngine &D = S.getDiagnostics(); 773 DefaultPolicy.enableCheckUnreachable = (unsigned) 774 (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) != 775 DiagnosticsEngine::Ignored); 776 DefaultPolicy.enableThreadSafetyAnalysis = (unsigned) 777 (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) != 778 DiagnosticsEngine::Ignored); 779 780} 781 782static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) { 783 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 784 i = fscope->PossiblyUnreachableDiags.begin(), 785 e = fscope->PossiblyUnreachableDiags.end(); 786 i != e; ++i) { 787 const sema::PossiblyUnreachableDiag &D = *i; 788 S.Diag(D.Loc, D.PD); 789 } 790} 791 792void clang::sema:: 793AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P, 794 sema::FunctionScopeInfo *fscope, 795 const Decl *D, const BlockExpr *blkExpr) { 796 797 // We avoid doing analysis-based warnings when there are errors for 798 // two reasons: 799 // (1) The CFGs often can't be constructed (if the body is invalid), so 800 // don't bother trying. 801 // (2) The code already has problems; running the analysis just takes more 802 // time. 803 DiagnosticsEngine &Diags = S.getDiagnostics(); 804 805 // Do not do any analysis for declarations in system headers if we are 806 // going to just ignore them. 807 if (Diags.getSuppressSystemWarnings() && 808 S.SourceMgr.isInSystemHeader(D->getLocation())) 809 return; 810 811 // For code in dependent contexts, we'll do this at instantiation time. 812 if (cast<DeclContext>(D)->isDependentContext()) 813 return; 814 815 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) { 816 // Flush out any possibly unreachable diagnostics. 817 flushDiagnostics(S, fscope); 818 return; 819 } 820 821 const Stmt *Body = D->getBody(); 822 assert(Body); 823 824 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D, 0); 825 826 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2 827 // explosion for destrutors that can result and the compile time hit. 828 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true; 829 AC.getCFGBuildOptions().AddEHEdges = false; 830 AC.getCFGBuildOptions().AddInitializers = true; 831 AC.getCFGBuildOptions().AddImplicitDtors = true; 832 833 // Force that certain expressions appear as CFGElements in the CFG. This 834 // is used to speed up various analyses. 835 // FIXME: This isn't the right factoring. This is here for initial 836 // prototyping, but we need a way for analyses to say what expressions they 837 // expect to always be CFGElements and then fill in the BuildOptions 838 // appropriately. This is essentially a layering violation. 839 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) { 840 // Unreachable code analysis and thread safety require a linearized CFG. 841 AC.getCFGBuildOptions().setAllAlwaysAdd(); 842 } 843 else { 844 AC.getCFGBuildOptions() 845 .setAlwaysAdd(Stmt::BinaryOperatorClass) 846 .setAlwaysAdd(Stmt::BlockExprClass) 847 .setAlwaysAdd(Stmt::CStyleCastExprClass) 848 .setAlwaysAdd(Stmt::DeclRefExprClass) 849 .setAlwaysAdd(Stmt::ImplicitCastExprClass) 850 .setAlwaysAdd(Stmt::UnaryOperatorClass); 851 } 852 853 // Construct the analysis context with the specified CFG build options. 854 855 // Emit delayed diagnostics. 856 if (!fscope->PossiblyUnreachableDiags.empty()) { 857 bool analyzed = false; 858 859 // Register the expressions with the CFGBuilder. 860 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 861 i = fscope->PossiblyUnreachableDiags.begin(), 862 e = fscope->PossiblyUnreachableDiags.end(); 863 i != e; ++i) { 864 if (const Stmt *stmt = i->stmt) 865 AC.registerForcedBlockExpression(stmt); 866 } 867 868 if (AC.getCFG()) { 869 analyzed = true; 870 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 871 i = fscope->PossiblyUnreachableDiags.begin(), 872 e = fscope->PossiblyUnreachableDiags.end(); 873 i != e; ++i) 874 { 875 const sema::PossiblyUnreachableDiag &D = *i; 876 bool processed = false; 877 if (const Stmt *stmt = i->stmt) { 878 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt); 879 assert(block); 880 if (CFGReverseBlockReachabilityAnalysis *cra = AC.getCFGReachablityAnalysis()) { 881 // Can this block be reached from the entrance? 882 if (cra->isReachable(&AC.getCFG()->getEntry(), block)) 883 S.Diag(D.Loc, D.PD); 884 processed = true; 885 } 886 } 887 if (!processed) { 888 // Emit the warning anyway if we cannot map to a basic block. 889 S.Diag(D.Loc, D.PD); 890 } 891 } 892 } 893 894 if (!analyzed) 895 flushDiagnostics(S, fscope); 896 } 897 898 899 // Warning: check missing 'return' 900 if (P.enableCheckFallThrough) { 901 const CheckFallThroughDiagnostics &CD = 902 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock() 903 : CheckFallThroughDiagnostics::MakeForFunction(D)); 904 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC); 905 } 906 907 // Warning: check for unreachable code 908 if (P.enableCheckUnreachable) { 909 // Only check for unreachable code on non-template instantiations. 910 // Different template instantiations can effectively change the control-flow 911 // and it is very difficult to prove that a snippet of code in a template 912 // is unreachable for all instantiations. 913 bool isTemplateInstantiation = false; 914 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 915 isTemplateInstantiation = Function->isTemplateInstantiation(); 916 if (!isTemplateInstantiation) 917 CheckUnreachable(S, AC); 918 } 919 920 // Check for thread safety violations 921 if (P.enableThreadSafetyAnalysis) { 922 SourceLocation FL = AC.getDecl()->getLocation(); 923 thread_safety::ThreadSafetyReporter Reporter(S, FL); 924 thread_safety::runThreadSafetyAnalysis(AC, Reporter); 925 Reporter.emitDiagnostics(); 926 } 927 928 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart()) 929 != DiagnosticsEngine::Ignored || 930 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart()) 931 != DiagnosticsEngine::Ignored) { 932 if (CFG *cfg = AC.getCFG()) { 933 UninitValsDiagReporter reporter(S); 934 UninitVariablesAnalysisStats stats; 935 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats)); 936 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC, 937 reporter, stats); 938 939 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) { 940 ++NumUninitAnalysisFunctions; 941 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed; 942 NumUninitAnalysisBlockVisits += stats.NumBlockVisits; 943 MaxUninitAnalysisVariablesPerFunction = 944 std::max(MaxUninitAnalysisVariablesPerFunction, 945 stats.NumVariablesAnalyzed); 946 MaxUninitAnalysisBlockVisitsPerFunction = 947 std::max(MaxUninitAnalysisBlockVisitsPerFunction, 948 stats.NumBlockVisits); 949 } 950 } 951 } 952 953 // Collect statistics about the CFG if it was built. 954 if (S.CollectStats && AC.isCFGBuilt()) { 955 ++NumFunctionsAnalyzed; 956 if (CFG *cfg = AC.getCFG()) { 957 // If we successfully built a CFG for this context, record some more 958 // detail information about it. 959 NumCFGBlocks += cfg->getNumBlockIDs(); 960 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction, 961 cfg->getNumBlockIDs()); 962 } else { 963 ++NumFunctionsWithBadCFGs; 964 } 965 } 966} 967 968void clang::sema::AnalysisBasedWarnings::PrintStats() const { 969 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n"; 970 971 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs; 972 unsigned AvgCFGBlocksPerFunction = 973 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt; 974 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed (" 975 << NumFunctionsWithBadCFGs << " w/o CFGs).\n" 976 << " " << NumCFGBlocks << " CFG blocks built.\n" 977 << " " << AvgCFGBlocksPerFunction 978 << " average CFG blocks per function.\n" 979 << " " << MaxCFGBlocksPerFunction 980 << " max CFG blocks per function.\n"; 981 982 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0 983 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions; 984 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0 985 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions; 986 llvm::errs() << NumUninitAnalysisFunctions 987 << " functions analyzed for uninitialiazed variables\n" 988 << " " << NumUninitAnalysisVariables << " variables analyzed.\n" 989 << " " << AvgUninitVariablesPerFunction 990 << " average variables per function.\n" 991 << " " << MaxUninitAnalysisVariablesPerFunction 992 << " max variables per function.\n" 993 << " " << NumUninitAnalysisBlockVisits << " block visits.\n" 994 << " " << AvgUninitBlockVisitsPerFunction 995 << " average block visits per function.\n" 996 << " " << MaxUninitAnalysisBlockVisitsPerFunction 997 << " max block visits per function.\n"; 998} 999