AnalysisConsumer.cpp revision 24146975f1af8c1b4b14e8545f218129d0e7dfeb
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 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// "Meta" ASTConsumer for running different source analyses. 11// 12//===----------------------------------------------------------------------===// 13 14#define DEBUG_TYPE "AnalysisConsumer" 15 16#include "AnalysisConsumer.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/Decl.h" 19#include "clang/AST/DeclCXX.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ParentMap.h" 22#include "clang/AST/RecursiveASTVisitor.h" 23#include "clang/Analysis/Analyses/LiveVariables.h" 24#include "clang/Analysis/CFG.h" 25#include "clang/Analysis/CallGraph.h" 26#include "clang/Basic/FileManager.h" 27#include "clang/Basic/SourceManager.h" 28#include "clang/Lex/Preprocessor.h" 29#include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 30#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 31#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 32#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 33#include "clang/StaticAnalyzer/Core/CheckerManager.h" 34#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 35#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 36#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 37#include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h" 38#include "llvm/ADT/DepthFirstIterator.h" 39#include "llvm/ADT/OwningPtr.h" 40#include "llvm/ADT/PostOrderIterator.h" 41#include "llvm/ADT/SmallPtrSet.h" 42#include "llvm/ADT/Statistic.h" 43#include "llvm/Support/FileSystem.h" 44#include "llvm/Support/Path.h" 45#include "llvm/Support/Program.h" 46#include "llvm/Support/Timer.h" 47#include "llvm/Support/raw_ostream.h" 48#include <queue> 49 50using namespace clang; 51using namespace ento; 52using llvm::SmallPtrSet; 53 54static ExplodedNode::Auditor* CreateUbiViz(); 55 56STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 57STATISTIC(NumFunctionsAnalyzed, 58 "The # of functions and blocks analyzed (as top level " 59 "with inlining turned on)."); 60STATISTIC(NumBlocksInAnalyzedFunctions, 61 "The # of basic blocks in the analyzed functions."); 62STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 63STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 64 65//===----------------------------------------------------------------------===// 66// Special PathDiagnosticConsumers. 67//===----------------------------------------------------------------------===// 68 69void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 70 PathDiagnosticConsumers &C, 71 const std::string &prefix, 72 const Preprocessor &PP) { 73 createHTMLDiagnosticConsumer(AnalyzerOpts, C, 74 llvm::sys::path::parent_path(prefix), PP); 75 createPlistDiagnosticConsumer(AnalyzerOpts, C, prefix, PP); 76} 77 78void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts, 79 PathDiagnosticConsumers &C, 80 const std::string &Prefix, 81 const clang::Preprocessor &PP) { 82 llvm_unreachable("'text' consumer should be enabled on ClangDiags"); 83} 84 85namespace { 86class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer { 87 DiagnosticsEngine &Diag; 88 bool IncludePath; 89public: 90 ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag) 91 : Diag(Diag), IncludePath(false) {} 92 virtual ~ClangDiagPathDiagConsumer() {} 93 virtual StringRef getName() const { return "ClangDiags"; } 94 95 virtual bool supportsLogicalOpControlFlow() const { return true; } 96 virtual bool supportsCrossFileDiagnostics() const { return true; } 97 98 virtual PathGenerationScheme getGenerationScheme() const { 99 return IncludePath ? Minimal : None; 100 } 101 102 void enablePaths() { 103 IncludePath = true; 104 } 105 106 void emitDiag(SourceLocation L, unsigned DiagID, 107 ArrayRef<SourceRange> Ranges) { 108 DiagnosticBuilder DiagBuilder = Diag.Report(L, DiagID); 109 110 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end(); 111 I != E; ++I) { 112 DiagBuilder << *I; 113 } 114 } 115 116 void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, 117 FilesMade *filesMade) { 118 for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(), 119 E = Diags.end(); I != E; ++I) { 120 const PathDiagnostic *PD = *I; 121 StringRef desc = PD->getShortDescription(); 122 SmallString<512> TmpStr; 123 llvm::raw_svector_ostream Out(TmpStr); 124 for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I) { 125 if (*I == '%') 126 Out << "%%"; 127 else 128 Out << *I; 129 } 130 Out.flush(); 131 unsigned ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, 132 TmpStr); 133 SourceLocation L = PD->getLocation().asLocation(); 134 emitDiag(L, ErrorDiag, PD->path.back()->getRanges()); 135 136 if (!IncludePath) 137 continue; 138 139 PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true); 140 for (PathPieces::const_iterator PI = FlatPath.begin(), 141 PE = FlatPath.end(); 142 PI != PE; ++PI) { 143 unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, 144 (*PI)->getString()); 145 146 SourceLocation NoteLoc = (*PI)->getLocation().asLocation(); 147 emitDiag(NoteLoc, NoteID, (*PI)->getRanges()); 148 } 149 } 150 } 151}; 152} // end anonymous namespace 153 154//===----------------------------------------------------------------------===// 155// AnalysisConsumer declaration. 156//===----------------------------------------------------------------------===// 157 158namespace { 159 160class AnalysisConsumer : public ASTConsumer, 161 public RecursiveASTVisitor<AnalysisConsumer> { 162 enum { 163 AM_None = 0, 164 AM_Syntax = 0x1, 165 AM_Path = 0x2 166 }; 167 typedef unsigned AnalysisMode; 168 169 /// Mode of the analyzes while recursively visiting Decls. 170 AnalysisMode RecVisitorMode; 171 /// Bug Reporter to use while recursively visiting Decls. 172 BugReporter *RecVisitorBR; 173 174public: 175 ASTContext *Ctx; 176 const Preprocessor &PP; 177 const std::string OutDir; 178 AnalyzerOptionsRef Opts; 179 ArrayRef<std::string> Plugins; 180 181 /// \brief Stores the declarations from the local translation unit. 182 /// Note, we pre-compute the local declarations at parse time as an 183 /// optimization to make sure we do not deserialize everything from disk. 184 /// The local declaration to all declarations ratio might be very small when 185 /// working with a PCH file. 186 SetOfDecls LocalTUDecls; 187 188 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 189 PathDiagnosticConsumers PathConsumers; 190 191 StoreManagerCreator CreateStoreMgr; 192 ConstraintManagerCreator CreateConstraintMgr; 193 194 OwningPtr<CheckerManager> checkerMgr; 195 OwningPtr<AnalysisManager> Mgr; 196 197 /// Time the analyzes time of each translation unit. 198 static llvm::Timer* TUTotalTimer; 199 200 /// The information about analyzed functions shared throughout the 201 /// translation unit. 202 FunctionSummariesTy FunctionSummaries; 203 204 AnalysisConsumer(const Preprocessor& pp, 205 const std::string& outdir, 206 AnalyzerOptionsRef opts, 207 ArrayRef<std::string> plugins) 208 : RecVisitorMode(0), RecVisitorBR(0), 209 Ctx(0), PP(pp), OutDir(outdir), Opts(opts), Plugins(plugins) { 210 DigestAnalyzerOptions(); 211 if (Opts->PrintStats) { 212 llvm::EnableStatistics(); 213 TUTotalTimer = new llvm::Timer("Analyzer Total Time"); 214 } 215 } 216 217 ~AnalysisConsumer() { 218 if (Opts->PrintStats) 219 delete TUTotalTimer; 220 } 221 222 void DigestAnalyzerOptions() { 223 // Create the PathDiagnosticConsumer. 224 ClangDiagPathDiagConsumer *clangDiags = 225 new ClangDiagPathDiagConsumer(PP.getDiagnostics()); 226 PathConsumers.push_back(clangDiags); 227 228 if (Opts->AnalysisDiagOpt == PD_TEXT) { 229 clangDiags->enablePaths(); 230 231 } else if (!OutDir.empty()) { 232 switch (Opts->AnalysisDiagOpt) { 233 default: 234#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \ 235 case PD_##NAME: CREATEFN(*Opts.getPtr(), PathConsumers, OutDir, PP);\ 236 break; 237#include "clang/StaticAnalyzer/Core/Analyses.def" 238 } 239 } 240 241 // Create the analyzer component creators. 242 switch (Opts->AnalysisStoreOpt) { 243 default: 244 llvm_unreachable("Unknown store manager."); 245#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 246 case NAME##Model: CreateStoreMgr = CREATEFN; break; 247#include "clang/StaticAnalyzer/Core/Analyses.def" 248 } 249 250 switch (Opts->AnalysisConstraintsOpt) { 251 default: 252 llvm_unreachable("Unknown constraint manager."); 253#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 254 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 255#include "clang/StaticAnalyzer/Core/Analyses.def" 256 } 257 } 258 259 void DisplayFunction(const Decl *D, AnalysisMode Mode, 260 ExprEngine::InliningModes IMode) { 261 if (!Opts->AnalyzerDisplayProgress) 262 return; 263 264 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 265 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 266 if (Loc.isValid()) { 267 llvm::errs() << "ANALYZE"; 268 269 if (Mode == AM_Syntax) 270 llvm::errs() << " (Syntax)"; 271 else if (Mode == AM_Path) { 272 llvm::errs() << " (Path, "; 273 switch (IMode) { 274 case ExprEngine::Inline_Minimal: 275 llvm::errs() << " Inline_Minimal"; 276 break; 277 case ExprEngine::Inline_Regular: 278 llvm::errs() << " Inline_Regular"; 279 break; 280 } 281 llvm::errs() << ")"; 282 } 283 else 284 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 285 286 llvm::errs() << ": " << Loc.getFilename(); 287 if (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)) { 288 const NamedDecl *ND = cast<NamedDecl>(D); 289 llvm::errs() << ' ' << *ND << '\n'; 290 } 291 else if (isa<BlockDecl>(D)) { 292 llvm::errs() << ' ' << "block(line:" << Loc.getLine() << ",col:" 293 << Loc.getColumn() << '\n'; 294 } 295 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 296 Selector S = MD->getSelector(); 297 llvm::errs() << ' ' << S.getAsString(); 298 } 299 } 300 } 301 302 virtual void Initialize(ASTContext &Context) { 303 Ctx = &Context; 304 checkerMgr.reset(createCheckerManager(*Opts, PP.getLangOpts(), Plugins, 305 PP.getDiagnostics())); 306 Mgr.reset(new AnalysisManager(*Ctx, 307 PP.getDiagnostics(), 308 PP.getLangOpts(), 309 PathConsumers, 310 CreateStoreMgr, 311 CreateConstraintMgr, 312 checkerMgr.get(), 313 *Opts)); 314 } 315 316 /// \brief Store the top level decls in the set to be processed later on. 317 /// (Doing this pre-processing avoids deserialization of data from PCH.) 318 virtual bool HandleTopLevelDecl(DeclGroupRef D); 319 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D); 320 321 virtual void HandleTranslationUnit(ASTContext &C); 322 323 /// \brief Determine which inlining mode should be used when this function is 324 /// analyzed. This allows to redefine the default inlining policies when 325 /// analyzing a given function. 326 ExprEngine::InliningModes 327 getInliningModeForFunction(const Decl *D, SetOfConstDecls Visited); 328 329 /// \brief Build the call graph for all the top level decls of this TU and 330 /// use it to define the order in which the functions should be visited. 331 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 332 333 /// \brief Run analyzes(syntax or path sensitive) on the given function. 334 /// \param Mode - determines if we are requesting syntax only or path 335 /// sensitive only analysis. 336 /// \param VisitedCallees - The output parameter, which is populated with the 337 /// set of functions which should be considered analyzed after analyzing the 338 /// given root function. 339 void HandleCode(Decl *D, AnalysisMode Mode, 340 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal, 341 SetOfConstDecls *VisitedCallees = 0); 342 343 void RunPathSensitiveChecks(Decl *D, 344 ExprEngine::InliningModes IMode, 345 SetOfConstDecls *VisitedCallees); 346 void ActionExprEngine(Decl *D, bool ObjCGCEnabled, 347 ExprEngine::InliningModes IMode, 348 SetOfConstDecls *VisitedCallees); 349 350 /// Visitors for the RecursiveASTVisitor. 351 bool shouldWalkTypesOfTypeLocs() const { return false; } 352 353 /// Handle callbacks for arbitrary Decls. 354 bool VisitDecl(Decl *D) { 355 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 356 if (Mode & AM_Syntax) 357 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 358 return true; 359 } 360 361 bool VisitFunctionDecl(FunctionDecl *FD) { 362 IdentifierInfo *II = FD->getIdentifier(); 363 if (II && II->getName().startswith("__inline")) 364 return true; 365 366 // We skip function template definitions, as their semantics is 367 // only determined when they are instantiated. 368 if (FD->isThisDeclarationADefinition() && 369 !FD->isDependentContext()) { 370 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 371 HandleCode(FD, RecVisitorMode); 372 } 373 return true; 374 } 375 376 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 377 if (MD->isThisDeclarationADefinition()) { 378 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 379 HandleCode(MD, RecVisitorMode); 380 } 381 return true; 382 } 383 384 bool VisitBlockDecl(BlockDecl *BD) { 385 if (BD->hasBody()) { 386 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 387 HandleCode(BD, RecVisitorMode); 388 } 389 return true; 390 } 391 392private: 393 void storeTopLevelDecls(DeclGroupRef DG); 394 395 /// \brief Check if we should skip (not analyze) the given function. 396 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 397 398}; 399} // end anonymous namespace 400 401 402//===----------------------------------------------------------------------===// 403// AnalysisConsumer implementation. 404//===----------------------------------------------------------------------===// 405llvm::Timer* AnalysisConsumer::TUTotalTimer = 0; 406 407bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 408 storeTopLevelDecls(DG); 409 return true; 410} 411 412void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 413 storeTopLevelDecls(DG); 414} 415 416void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 417 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 418 419 // Skip ObjCMethodDecl, wait for the objc container to avoid 420 // analyzing twice. 421 if (isa<ObjCMethodDecl>(*I)) 422 continue; 423 424 LocalTUDecls.push_back(*I); 425 } 426} 427 428static bool shouldSkipFunction(const Decl *D, 429 SetOfConstDecls Visited, 430 SetOfConstDecls VisitedAsTopLevel) { 431 if (VisitedAsTopLevel.count(D)) 432 return true; 433 434 // We want to re-analyse the functions as top level in the following cases: 435 // - The 'init' methods should be reanalyzed because 436 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 437 // 'nil' and unless we analyze the 'init' functions as top level, we will 438 // not catch errors within defensive code. 439 // - We want to reanalyze all ObjC methods as top level to report Retain 440 // Count naming convention errors more aggressively. 441 if (isa<ObjCMethodDecl>(D)) 442 return false; 443 444 // Otherwise, if we visited the function before, do not reanalyze it. 445 return Visited.count(D); 446} 447 448ExprEngine::InliningModes 449AnalysisConsumer::getInliningModeForFunction(const Decl *D, 450 SetOfConstDecls Visited) { 451 // We want to reanalyze all ObjC methods as top level to report Retain 452 // Count naming convention errors more aggressively. But we should tune down 453 // inlining when reanalyzing an already inlined function. 454 if (Visited.count(D)) { 455 assert(isa<ObjCMethodDecl>(D) && 456 "We are only reanalyzing ObjCMethods."); 457 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D); 458 if (ObjCM->getMethodFamily() != OMF_init) 459 return ExprEngine::Inline_Minimal; 460 } 461 462 return ExprEngine::Inline_Regular; 463} 464 465void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 466 // Build the Call Graph by adding all the top level declarations to the graph. 467 // Note: CallGraph can trigger deserialization of more items from a pch 468 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 469 // We rely on random access to add the initially processed Decls to CG. 470 CallGraph CG; 471 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 472 CG.addToCallGraph(LocalTUDecls[i]); 473 } 474 475 // Walk over all of the call graph nodes in topological order, so that we 476 // analyze parents before the children. Skip the functions inlined into 477 // the previously processed functions. Use external Visited set to identify 478 // inlined functions. The topological order allows the "do not reanalyze 479 // previously inlined function" performance heuristic to be triggered more 480 // often. 481 SetOfConstDecls Visited; 482 SetOfConstDecls VisitedAsTopLevel; 483 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG); 484 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator 485 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 486 NumFunctionTopLevel++; 487 488 CallGraphNode *N = *I; 489 Decl *D = N->getDecl(); 490 491 // Skip the abstract root node. 492 if (!D) 493 continue; 494 495 // Skip the functions which have been processed already or previously 496 // inlined. 497 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel)) 498 continue; 499 500 // Analyze the function. 501 SetOfConstDecls VisitedCallees; 502 503 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited), 504 (Mgr->options.InliningMode == All ? 0 : &VisitedCallees)); 505 506 // Add the visited callees to the global visited set. 507 for (SetOfConstDecls::iterator I = VisitedCallees.begin(), 508 E = VisitedCallees.end(); I != E; ++I) { 509 Visited.insert(*I); 510 } 511 VisitedAsTopLevel.insert(D); 512 } 513} 514 515void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 516 // Don't run the actions if an error has occurred with parsing the file. 517 DiagnosticsEngine &Diags = PP.getDiagnostics(); 518 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 519 return; 520 521 { 522 if (TUTotalTimer) TUTotalTimer->startTimer(); 523 524 // Introduce a scope to destroy BR before Mgr. 525 BugReporter BR(*Mgr); 526 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 527 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 528 529 // Run the AST-only checks using the order in which functions are defined. 530 // If inlining is not turned on, use the simplest function order for path 531 // sensitive analyzes as well. 532 RecVisitorMode = AM_Syntax; 533 if (!Mgr->shouldInlineCall()) 534 RecVisitorMode |= AM_Path; 535 RecVisitorBR = &BR; 536 537 // Process all the top level declarations. 538 // 539 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 540 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 541 // random access. By doing so, we automatically compensate for iterators 542 // possibly being invalidated, although this is a bit slower. 543 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 544 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 545 TraverseDecl(LocalTUDecls[i]); 546 } 547 548 if (Mgr->shouldInlineCall()) 549 HandleDeclsCallGraph(LocalTUDeclsSize); 550 551 // After all decls handled, run checkers on the entire TranslationUnit. 552 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 553 554 RecVisitorBR = 0; 555 } 556 557 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 558 // FIXME: This should be replaced with something that doesn't rely on 559 // side-effects in PathDiagnosticConsumer's destructor. This is required when 560 // used with option -disable-free. 561 Mgr.reset(NULL); 562 563 if (TUTotalTimer) TUTotalTimer->stopTimer(); 564 565 // Count how many basic blocks we have not covered. 566 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 567 if (NumBlocksInAnalyzedFunctions > 0) 568 PercentReachableBlocks = 569 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 570 NumBlocksInAnalyzedFunctions; 571 572} 573 574static std::string getFunctionName(const Decl *D) { 575 if (const ObjCMethodDecl *ID = dyn_cast<ObjCMethodDecl>(D)) { 576 return ID->getSelector().getAsString(); 577 } 578 if (const FunctionDecl *ND = dyn_cast<FunctionDecl>(D)) { 579 IdentifierInfo *II = ND->getIdentifier(); 580 if (II) 581 return II->getName(); 582 } 583 return ""; 584} 585 586AnalysisConsumer::AnalysisMode 587AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 588 if (!Opts->AnalyzeSpecificFunction.empty() && 589 getFunctionName(D) != Opts->AnalyzeSpecificFunction) 590 return AM_None; 591 592 // Unless -analyze-all is specified, treat decls differently depending on 593 // where they came from: 594 // - Main source file: run both path-sensitive and non-path-sensitive checks. 595 // - Header files: run non-path-sensitive checks only. 596 // - System headers: don't run any checks. 597 SourceManager &SM = Ctx->getSourceManager(); 598 SourceLocation SL = SM.getExpansionLoc(D->getLocation()); 599 if (!Opts->AnalyzeAll && !SM.isInMainFile(SL)) { 600 if (SL.isInvalid() || SM.isInSystemHeader(SL)) 601 return AM_None; 602 return Mode & ~AM_Path; 603 } 604 605 return Mode; 606} 607 608void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 609 ExprEngine::InliningModes IMode, 610 SetOfConstDecls *VisitedCallees) { 611 if (!D->hasBody()) 612 return; 613 Mode = getModeForDecl(D, Mode); 614 if (Mode == AM_None) 615 return; 616 617 DisplayFunction(D, Mode, IMode); 618 CFG *DeclCFG = Mgr->getCFG(D); 619 if (DeclCFG) { 620 unsigned CFGSize = DeclCFG->size(); 621 MaxCFGSize = MaxCFGSize < CFGSize ? CFGSize : MaxCFGSize; 622 } 623 624 // Clear the AnalysisManager of old AnalysisDeclContexts. 625 Mgr->ClearContexts(); 626 BugReporter BR(*Mgr); 627 628 if (Mode & AM_Syntax) 629 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR); 630 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 631 RunPathSensitiveChecks(D, IMode, VisitedCallees); 632 if (IMode != ExprEngine::Inline_Minimal) 633 NumFunctionsAnalyzed++; 634 } 635} 636 637//===----------------------------------------------------------------------===// 638// Path-sensitive checking. 639//===----------------------------------------------------------------------===// 640 641void AnalysisConsumer::ActionExprEngine(Decl *D, bool ObjCGCEnabled, 642 ExprEngine::InliningModes IMode, 643 SetOfConstDecls *VisitedCallees) { 644 // Construct the analysis engine. First check if the CFG is valid. 645 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 646 if (!Mgr->getCFG(D)) 647 return; 648 649 // See if the LiveVariables analysis scales. 650 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 651 return; 652 653 ExprEngine Eng(*Mgr, ObjCGCEnabled, VisitedCallees, &FunctionSummaries,IMode); 654 655 // Set the graph auditor. 656 OwningPtr<ExplodedNode::Auditor> Auditor; 657 if (Mgr->options.visualizeExplodedGraphWithUbiGraph) { 658 Auditor.reset(CreateUbiViz()); 659 ExplodedNode::SetAuditor(Auditor.get()); 660 } 661 662 // Execute the worklist algorithm. 663 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 664 Mgr->options.getMaxNodesPerTopLevelFunction()); 665 666 // Release the auditor (if any) so that it doesn't monitor the graph 667 // created BugReporter. 668 ExplodedNode::SetAuditor(0); 669 670 // Visualize the exploded graph. 671 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 672 Eng.ViewGraph(Mgr->options.TrimGraph); 673 674 // Display warnings. 675 Eng.getBugReporter().FlushReports(); 676} 677 678void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 679 ExprEngine::InliningModes IMode, 680 SetOfConstDecls *Visited) { 681 682 switch (Mgr->getLangOpts().getGC()) { 683 case LangOptions::NonGC: 684 ActionExprEngine(D, false, IMode, Visited); 685 break; 686 687 case LangOptions::GCOnly: 688 ActionExprEngine(D, true, IMode, Visited); 689 break; 690 691 case LangOptions::HybridGC: 692 ActionExprEngine(D, false, IMode, Visited); 693 ActionExprEngine(D, true, IMode, Visited); 694 break; 695 } 696} 697 698//===----------------------------------------------------------------------===// 699// AnalysisConsumer creation. 700//===----------------------------------------------------------------------===// 701 702ASTConsumer* ento::CreateAnalysisConsumer(const Preprocessor& pp, 703 const std::string& outDir, 704 AnalyzerOptionsRef opts, 705 ArrayRef<std::string> plugins) { 706 // Disable the effects of '-Werror' when using the AnalysisConsumer. 707 pp.getDiagnostics().setWarningsAsErrors(false); 708 709 return new AnalysisConsumer(pp, outDir, opts, plugins); 710} 711 712//===----------------------------------------------------------------------===// 713// Ubigraph Visualization. FIXME: Move to separate file. 714//===----------------------------------------------------------------------===// 715 716namespace { 717 718class UbigraphViz : public ExplodedNode::Auditor { 719 OwningPtr<raw_ostream> Out; 720 std::string Filename; 721 unsigned Cntr; 722 723 typedef llvm::DenseMap<void*,unsigned> VMap; 724 VMap M; 725 726public: 727 UbigraphViz(raw_ostream *Out, StringRef Filename); 728 729 ~UbigraphViz(); 730 731 virtual void AddEdge(ExplodedNode *Src, ExplodedNode *Dst); 732}; 733 734} // end anonymous namespace 735 736static ExplodedNode::Auditor* CreateUbiViz() { 737 SmallString<128> P; 738 int FD; 739 llvm::sys::fs::createTemporaryFile("llvm_ubi", "", FD, P); 740 llvm::errs() << "Writing '" << P.str() << "'.\n"; 741 742 OwningPtr<llvm::raw_fd_ostream> Stream; 743 Stream.reset(new llvm::raw_fd_ostream(FD, true)); 744 745 return new UbigraphViz(Stream.take(), P); 746} 747 748void UbigraphViz::AddEdge(ExplodedNode *Src, ExplodedNode *Dst) { 749 750 assert (Src != Dst && "Self-edges are not allowed."); 751 752 // Lookup the Src. If it is a new node, it's a root. 753 VMap::iterator SrcI= M.find(Src); 754 unsigned SrcID; 755 756 if (SrcI == M.end()) { 757 M[Src] = SrcID = Cntr++; 758 *Out << "('vertex', " << SrcID << ", ('color','#00ff00'))\n"; 759 } 760 else 761 SrcID = SrcI->second; 762 763 // Lookup the Dst. 764 VMap::iterator DstI= M.find(Dst); 765 unsigned DstID; 766 767 if (DstI == M.end()) { 768 M[Dst] = DstID = Cntr++; 769 *Out << "('vertex', " << DstID << ")\n"; 770 } 771 else { 772 // We have hit DstID before. Change its style to reflect a cache hit. 773 DstID = DstI->second; 774 *Out << "('change_vertex_style', " << DstID << ", 1)\n"; 775 } 776 777 // Add the edge. 778 *Out << "('edge', " << SrcID << ", " << DstID 779 << ", ('arrow','true'), ('oriented', 'true'))\n"; 780} 781 782UbigraphViz::UbigraphViz(raw_ostream *Out, StringRef Filename) 783 : Out(Out), Filename(Filename), Cntr(0) { 784 785 *Out << "('vertex_style_attribute', 0, ('shape', 'icosahedron'))\n"; 786 *Out << "('vertex_style', 1, 0, ('shape', 'sphere'), ('color', '#ffcc66')," 787 " ('size', '1.5'))\n"; 788} 789 790UbigraphViz::~UbigraphViz() { 791 Out.reset(0); 792 llvm::errs() << "Running 'ubiviz' program... "; 793 std::string ErrMsg; 794 std::string Ubiviz = llvm::sys::FindProgramByName("ubiviz"); 795 std::vector<const char*> args; 796 args.push_back(Ubiviz.c_str()); 797 args.push_back(Filename.c_str()); 798 args.push_back(0); 799 800 if (llvm::sys::ExecuteAndWait(Ubiviz, &args[0], 0, 0, 0, 0, &ErrMsg)) { 801 llvm::errs() << "Error viewing graph: " << ErrMsg << "\n"; 802 } 803 804 // Delete the file. 805 llvm::sys::fs::remove(Filename); 806} 807