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